Group Anagrams
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Group the words that are anagrams of each other.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1What do all anagrams of "eat" have in common?
- Hint 2Their letters, once sorted, are identical.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A post office sorts letters into pigeon-holes. For each word you write its letters in alphabetical order on a sticker: "eat", "tea" and "ate" all get the sticker "aet". Then each word simply goes into the pigeon-hole with its sticker. Words in the same hole are anagrams.
- The obvious way
Compare every pair of words as anagrams and merge groups: O(n² x length).
- The key insight
Give every word a sticker that is the same for all its anagrams (its letters sorted). A dictionary from sticker to the list of words does all the grouping in one pass.
- The algorithm
- Prepare empty pigeon-holes (a dictionary of lists).
- For each word, make its sticker by sorting its letters.
- Drop the word into the pigeon-hole with that sticker.
- At the end, every non-empty pigeon-hole is one group.
Watch it run
Examplewords = [eat, tea, tan, ate, nat, bat]
"eat" -> sticker aet. New hole, put eat in.
aet: [eat]
Where people slip
- In Python a list cannot be a dictionary key; join the letters into a string (or use a tuple).
- For lowercase words, a 26-count tuple as the sticker avoids sorting.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
from collections import defaultdict
def group_anagrams(words):
holes = defaultdict(list) # sticker -> words
for word in words:
sticker = "".join(sorted(word)) # letters in alphabetical order
holes[sticker].append(word)
return list(holes.values())Now close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.