Group Anagrams
Two words are anagrams if one can be rearranged into the other, such as listen and silent.
Write group_anagrams(words) that returns a list of groups, where each group is a list of the words that are anagrams of each other. The order of the groups, and the order of the words inside a group, does not matter. Every word must appear in exactly one group.
Understand the problem
Work out what the answer looks like.
How many groups does group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) return?
The groups are eat, tea, ate, then tan, nat, then bat alone. A word with no anagram partner is a group of one.
What should group_anagrams([]) return?
[][[]]None
No words, so no groups: an empty list of groups. [[]] would be one group that contains nothing.
Try examples by hand
Find something that stays the same inside a group.
What is "".join(sorted("tea"))? Type the result.
sorted("tea") gives the letters in alphabetical order, ["a", "e", "t"], and join glues them into "aet".
Which statement is true for all words in one anagram group?
- They have the same length only
- Their letters in alphabetical order are the same string
- They start with the same letter
Anagrams contain the same letters, so sorting the letters gives the same result for each word in the group, and a different result for words of different groups. That sorted string is a perfect label for the group.
Write the brute force
Do not look for the clever answer yet. Write the simplest version that is correct, even if it is slow. A correct slow answer gives you something to test against and something to improve.
def group_anagrams(words):
# Write the simple version here. It only has to be correct, not fast.
pass
Hint 1: a question to ask yourself
For one word, how do you decide which existing group it belongs to?
Hint 2: the shape of the answer
Keep a list of groups. For each word, go through the groups and compare the word with the first word of the group (same sorted letters?). If one matches, add the word there, otherwise start a new group.
Find the bottleneck
Before you improve anything, find what is slow. Answer these, then write the faster version.
Which part of the brute force repeats the most work?
- Sorting the letters of a word
- Comparing each new word with the groups one after another
- Creating a new group
Every new word is compared with groups one at a time until a match is found. With many groups, that is a long search for every word, and it also sorts the same group words again and again.
If each group had a label (the sorted letters), which structure finds the group for a label in one step?
- A list of groups
- A dictionary from label to group
- A string
A dictionary keyed by the label. Each word computes its label once and goes straight to its group, with no comparing against other groups.
Make it faster
Now write the version that never compares two words with each other.
def group_anagrams(words):
# Write the faster version here.
pass
Hint 1: a question to ask yourself
Can every word tell you, on its own, which group it belongs to?
Hint 2: the pattern
Use the sorted letters of the word as a dictionary key, and a list of words as the value.
Hint 3: pseudocode
groups = empty dictionary (label -> list of words)
for each word:
label = the letters of word in sorted order, joined into a string
add word to the list at groups[label] (create the list if it is new)
return the lists, as a list
Tip: groups.setdefault(label, []) gives you the list, creating it if needed.
Reflect
Brute force: compare with every group
def group_anagrams(words):
groups = []
for word in words:
for group in groups:
if sorted(word) == sorted(group[0]):
group.append(word)
break
else:
groups.append([word])
return groups
Improved: a dictionary with a label as key
def group_anagrams(words):
groups = {}
for word in words:
label = "".join(sorted(word))
groups.setdefault(label, []).append(word)
return list(groups.values())
Another way: a letter-count key, no sorting
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for word in words:
counts = [0] * 26
for ch in word:
counts[ord(ch) - ord("a")] += 1
groups[tuple(counts)].append(word)
return list(groups.values())
Pattern: design the key. The hard part of this problem is not the dictionary, it is choosing a key that is identical for everything in a group and different between groups. "Sorted letters" is such a key. Many hashing problems are really "find the right key", also called a canonical form.
Keys must be hashable: a string or a tuple can be a key; a list cannot (it can change). That is why the letter-count version converts its list to a tuple.
Cost (n words of length k):
| Version | Time |
|---|---|
| Compare with each group | O(n x groups x k log k) |
| Dictionary, sorted key | O(n x k log k) |
| Dictionary, count key | O(n x k) |
What an interviewer might ask next: The words may contain upper and lower case, and you should treat them as the same. Where in the code would you change it?
import random
def SAME(got, want):
return sorted(sorted(group) for group in got) == sorted(sorted(group) for group in want)
VISIBLE = 3
CASES = [
((['eat', 'tea', 'tan', 'ate', 'nat', 'bat'],), [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']], 'a normal list'),
(([],), [], 'no words'),
((['a'],), [['a']], 'one word'),
((['abc', 'cab', 'bca'],), [['abc', 'cab', 'bca']], 'one group of three'),
((['ab', 'cd', 'ef'],), [['ab'], ['cd'], ['ef']], 'no anagrams at all'),
((['aab', 'aba', 'abb'],), [['aab', 'aba'], ['abb']], 'repeated letters matter'),
((['', ''],), [['', '']], 'empty words'),
((['listen', 'silent', 'enlist', 'google', 'gogole'],), [['listen', 'silent', 'enlist'], ['google', 'gogole']], 'longer words'),
((['ab', 'ba', 'ab'],), [['ab', 'ba', 'ab']], 'the same word twice'),
]
def REFERENCE(words):
groups = {}
for word in words:
groups.setdefault(''.join(sorted(word)), []).append(word)
return list(groups.values())
LIMIT = 2.0
def PERF():
rng = random.Random(5)
words = [''.join(rng.choice('abcdefghijkl') for _ in range(6)) for _ in range(10000)]
return [('10000 words', (words,))]