Group Anagrams
Put words that are anagrams of each other into the same group, using sorted letters as a hash map key.
The problem
You get an array of strings strs made of lowercase English letters. Group together the words that are anagrams of each other, meaning they use the same letters the same number of times. Return the groups in any order, with the words inside each group in any order too.
Input strs = ["stop", "pots", "dusty", "tops", "study", "chai"]
Output [["stop", "pots", "tops"], ["dusty", "study"], ["chai"]]
stop, pots and tops share the letters o, p, s and t; dusty and study share theirs; chai has no partner.
Input strs = ["", "b", ""]
Output [["", ""], ["b"]]
The two empty strings use the same (zero) letters, so they form a group.
Key constraint: There can be up to 10,000 words of up to 100 letters each, so comparing every pair of words is too slow.
How to spot the pattern
- Words belong together when they have the same letters, whatever the order.
- You need to bucket items by a shared property, which is a job for a map from key to list.
The idea
Anagrams turn into the same string once you sort their letters: "stop", "pots" and "tops" all become "opst". So use the sorted word as a key in a hash map whose value is the list of words with that key. After one pass over the words, each list in the map is one group.
Brute force: Compare every word with every other word using an anagram check, which takes O(n^2 * k) time for n words of length k.
Step by step
- 1Create a map from a key string to a list of words.
- 2For each word, sort its letters to build its key.
- 3Append the word to the list stored under that key, starting a new list if the key is new.
- 4Return all the lists in the map.
See the pattern move
The hashing pattern on a small example. Step through it, or press play.
Code
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = defaultdict(list) # sorted letters -> words with those letters
for word in strs:
key = "".join(sorted(word))
groups[key].append(word)
return list(groups.values())Complexity
Time
O(n * k log k)
Space
O(n * k)
Each of the n words is sorted once, which costs k log k for a word of length k; the map stores every word plus one key per group.
Watch out for
- Using a list or array as the key: Python lists can't be dictionary keys (use a string or a tuple), and a Java
char[]key is compared by identity, not by its letters. - Building a key from letter counts without separators: counts like 1, 11 and 11, 1 both turn into "111", so different words collide.
Follow-up questions
Can you avoid sorting each word?
Use the 26 letter counts as the key, joined with a separator such as "#". Building it takes O(k) per word, so the total drops to O(n * k).
What if the words can contain any characters?
Sorted letters still work as a key. For a count key, switch from 26 slots to a map of character counts and write it out in a fixed order, so equal counts always give the same key.
In Hinglish
Har word ke letters sort karo, wahi uski key hai; same key wale saare words ek hi group mein jaate hain.