- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements