Group Anagrams
Group the words that are made of the same letters
DSA, Medium, Arrays & Hashing
Which structure or algorithm, and what does it cost.
A list words holds lowercase words. Put the words that are rearrangements of each other into one group. Return the list of groups. Order the groups by the first appearance of any of their words, and keep the words inside a group in input order. A word can be empty.
Examples
Constraints
- 1 <= number of words <= 10,000.
- Each word has 0 to 100 characters, all lowercase letters a to z.
Your answer must contain
- The simple method and why it is too slow; the better method; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n * L) time, where n is the number of words and L is the longest word.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Two words belong together when they are rearrangements of each other. What could you compute for each word that is the same for every rearrangement?
Hint 2 the approach
Make a signature for each word that does not change when its letters move. Use the signature as the name of a bucket and drop the word in it.
Hint 3 the key step
Sort the letters of each word to get its signature. Keep a dictionary from signature to list of words. The answer is its lists, in first-seen order.
Walkthrough
Full walkthrough brute force to best
Brute force
Take each word and compare it with the first word of every group made so far, using a letter count or a sort. If it matches, add it to that group. If no group matches, start a new one. With n words and up to n groups, that is n squared comparisons, each costing about L. For 10,000 words that is 100 million comparisons.
Better method
Give each word a signature, its letters in sorted order, joined into a string. Words in one group share the signature. A dictionary from signature to list of words collects them in one pass. Sorting a word costs L log L, so the total is O(n * L log L). It is shorter to write, and fine when words are short.
Best method
Count each letter a to z in the word, and use the 26 counts as the signature, written as a tuple so it can be a dictionary key. Building it costs one step per letter, so the total is O(n * L), with no sort. This is correct because two words are rearrangements exactly when they have the same count for every letter, and the signature is that list of counts. A dictionary keeps insertion order, so reading its values gives the groups in the order their first word appeared.
Hand trace
Run on ["stone", "notes", "tones", "pea", "ape", "bat"]. stone has one each of e, n, o, s and t and zero of the other letters. Call that key K1. It is new, so the group is [stone]. notes has the same counts, so it joins K1: [stone, notes]. tones also has K1: [stone, notes, tones]. pea has one each of a, e and p. That is a new key K2, so the group is [pea]. ape has K2: [pea, ape]. bat has one each of a, b and t, a new key K3: [bat]. The dictionary has three keys, so the result is [[stone, notes, tones], [pea, ape], [bat]].
Code
def group_anagrams(words):
groups = {}
for w in words:
counts = [0] * 26
for ch in w:
counts[ord(ch) - 97] += 1
groups.setdefault(tuple(counts), []).append(w)
return list(groups.values())Time and memory
O(n * L) time, because each word of length L is read once to fill 26 counts, and each dictionary step is O(1) on average. O(n * L) memory, because the groups hold every word. The keys add only 26 numbers per group.
Common mistakes
- Using a list of counts as the dictionary key. A list cannot be a key. Turn it into a tuple, or join sorted letters into a string.
- Using the set of letters as the signature. Then "aab" and "abb" land in one group, but they are not rearrangements.
- Adding up the letter codes as the signature. The words "ad" and "bc" have the same sum but different letters.
- Sorting the whole list of words instead of the letters inside each word. That never puts two anagrams next to each other.