Algorithms · Hash maps

Group Anagrams

Group words made of the same letters, like eat, tea and ate.

The problem

Put words that use exactly the same letters into the same group (eat, tea and ate are one group). Return the groups, in any order.

check(["eat", "tea", "tan", "ate", "nat", "bat"])[["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]
check([""])[[""]]
Hash maps. Remember what you’ve seen. A coat check: hand over your ticket and get your coat back instantly, however many coats there are.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def same_letters(a, b):do two words use the same letters?
return sorted(a) == sorted(b)sort both sets of letters and compare
def group_anagrams(words):take a list of words
groups = []no groups yet
for w in words:for each word
for g in groups:look through every group so far
if same_letters(g[0], w):does it belong here?
g.append(w)join this group
breakstop looking
else:no group matched
groups.append([w])start a new group
return groupshand back the groups

Now ask: what if there were a billion?

This is MapReduce in miniature: compute a key for every item (map), then gather items with the same key (reduce). Google ran this exact shape over the whole web.

Aim for O(n)🔥 boss

Think it through

What do eat, tea and ate have in common that you could compute from each word alone?

  • The same first letter
  • The same letters in alphabetical order: “aet”
Show the answer

The same letters in alphabetical order: “aet”. Sorting the letters gives every anagram the same label. A label you compute from each item on its own is a key.

Once every word has a key, how do you collect the groups?

  • Compare each word with every group
  • A dictionary from key to a list of words
Show the answer

A dictionary from key to a list of words. Group-by-key is one pass with a dictionary: each word goes straight to its list. Comparing with every group is the every-pair trap again.

Stuck? 3 nudges, smallest first
  1. Every word in a group has something in common you can compute: its letters in alphabetical order.
  2. Use that sorted-letters text as a key in a dictionary, and each value is a list of words.
  3. key = "".join(sorted(w)), then groups.setdefault(key, []).append(w). Return list(groups.values()).

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
def group_anagrams(words):take a list of words
groups = {}sorted letters → the words with those letters
for w in words:look at each word once
key = "".join(sorted(w))its letters in order: "tea" → "aet"
groups.setdefault(key, []).append(w)put it in that group (making it if needed)
return list(groups.values())just the groups

Where it’s used for real

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with hash maps