
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find the largest grouping of anagrams from a word list in Python
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 −
Example
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))
Input
["xy", "yx", "xyz", "zyx", "yzx", "wwwww"]
Output
3
- Related Articles
- Python program to find N largest elements from a list
- Python program to find word score from list of words
- Python program to find the largest number in a list
- Python program to find the character position of Kth word from a list of strings
- Python program to find largest number in a list
- Program to find largest distance pair from two list of numbers in Python
- Python Group Anagrams from given list
- Python program to find the second largest number in a list
- 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?
- Program to find largest sum of non-adjacent elements of a list in Python
- Program to find largest kth index value of one list in Python
- Grouping words with their anagrams in JavaScript
- Python Program to Find the Second Largest Number in a List Using Bubble Sort

Advertisements