- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a list of strings words, we have to group all anagrams together and return the size of the largest grouping.

So, if the input is like words = ["xy", "yx", "xyz", "zyx", "yzx", "wwwww"], then the output will be 3, as ["xyz", "zyx", "yzx"] is the largest grouping.

To solve this, we will follow these steps −

lookup := a new map, initially empty

res := 0

for each i in words, do

p := sort i in lexicographical way

if p is in lookup, increase count, otherwise 1

res := maximum of res and lookup[p]

return res

Let us see the following implementation to get better understanding −

class Solution: def solve(self, words): lookup = {} res = 0 for i in words: p = "".join(sorted(i)) lookup[p] = lookup.get(p, 0) + 1 res = max(res, lookup[p]) return res ob = Solution() words = ["xy", "yx", "xyz", "zyx", "yzx", "wwwww"] print(ob.solve(words))

["xy", "yx", "xyz", "zyx", "yzx", "wwwww"]

3

- Related Questions & Answers
- Python program to find word score from list of words
- Python program to find N largest elements from a list
- Python program to find the character position of Kth word from a list of strings
- Python program to find the largest number in a list
- Python Group Anagrams from given list
- Python program to find largest number in a list
- Python program to find the second largest number in a list
- Program to find largest distance pair from two list of numbers in Python
- Python Program to Find the Largest Element in a Doubly Linked List
- Program to find lexicographically largest mountain list in Python
- Python program to find Largest, Smallest, Second Largest, and Second Smallest in a List?
- Grouping words with their anagrams in JavaScript
- Program to find largest sum of non-adjacent elements of a list in Python
- Python Program to return the Length of the Longest Word from the List of Words
- Program to find Smallest and Largest Word in a String in C++

Advertisements