1Question
You are given an array of strings strs. Group the anagrams together and return the groups. You can return the groups in any order.
An anagram is a word made by re-arranging the letters of another word, using every letter exactly once. For example, "eat" and "tea" are anagrams. The order of the groups, and the order of the words inside a group, does not matter.
“eat”, “tea” and “ate” use the same letters. “tan” and “nat” use the same letters. “bat” is alone.
An empty string is only an anagram of another empty string. So it forms one group by itself.
One word makes one group.
Constraints
Up to 10,000 words. Comparing every pair of words is about 50 million comparisons. We can do it in one pass.
Each word is short. Sorting one word is cheap, so we can afford to sort every word.
Only 26 possible letters. This also lets us count letters with a fixed array of size 26.
2Hints
Open one hint at a time. Try to think before you open the next one.
3Pattern
Hash Map with a Canonical Key
Give every item a label that is the same for all items in its group. Then group by label.
Two anagrams look different, but they have one thing in common: the same sorted letters. That shared form is called a canonical key. A hash map from key → list of words then does all the grouping for us:
Every word is turned into a key once and added once. We never compare two words directly.
How to spot this pattern
- You must group items that are “the same” in some way.
- Items that belong together look different, but can be turned into one identical form (sorted, counted, normalised).
- The order of the groups in the answer does not matter.
- You are allowed O(n) extra memory for the map.
4Explanation
The big idea: Walk through the words once with a map called groups (key → list of words). For each word:
Sort the letters of the word: key = "".join(sorted(word)). For "tea" the key is "aet".
Append the word to groups[key]. If the key is new, start a new list.
Why does this work? Two words have the same sorted letters if and only if they are anagrams. So words with the same key are exactly one group.
What is the answer? Each key owns one list. The answer is all the lists: list(groups.values()).
5Brute Force
Compare each word with the groups we already have.
Idea
Keep a list of groups. For each word, look for a group it belongs to:
- Go through the existing groups one by one.
- Compare the word with the first word of the group. Are they anagrams?
- If yes, add the word to that group. If no group matches, start a new group.
def is_anagram(a, b):
if len(a) != len(b):
return False
count = {}
for ch in a:
count[ch] = count.get(ch, 0) + 1
for ch in b:
if count.get(ch, 0) == 0:
return False
count[ch] -= 1
return True
def group_anagrams_brute(strs):
groups = [] # list of lists
for word in strs:
placed = False
for group in groups:
if is_anagram(word, group[0]): # compare with the first word of the group
group.append(word)
placed = True
break
if not placed:
groups.append([word]) # no match: start a new group
return groups
print(group_anagrams_brute(["eat", "tea", "tan", "ate", "nat", "bat"]))
# [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]6Optimal Solution
One pass with a hash map from sorted word → list of words.
from collections import defaultdict
def group_anagrams(strs):
groups = defaultdict(list) # sorted word -> list of words
for word in strs:
key = "".join(sorted(word)) # same key for all anagrams
groups[key].append(word) # O(1) to find the group
return list(groups.values())
print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
# [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]7Time and Space Complexity
Let n be the number of items in the array.
Brute force
Optimal (hash map with sorted key)
How big is the difference?
Approximate number of word comparisons or word visits (worst case, k is at most 100):
| n | Brute force (n²/2) | Hash map (n) |
|---|---|---|
| 10 | 45 | 10 |
| 1,000 | 499,500 | 1,000 |
| 10,000 | about 50 million | 10,000 |
The hash map visits each word once. Even after paying k log k to sort each word, it does far less work for the biggest input.