Skip to content
BytePatterns

Group Anagrams

Hash Tables: lesson 4 of 5

Give every item a canonical key, then bucket by it.

Lesson 4 of 5 · 5 min

Group Anagrams

Step 1 of 6

Anagrams share their letters and differ only in order. So give every word a canonical form and let the map do the matching.

The Idea

Two words are anagrams when their letters match and only the order differs. So give each word a canonical signature — its letters sorted — and use that signature as a dictionary key. Words sharing a signature drop into the same bucket, and no two words are ever compared directly.

Real-World Example

A locksmith sorts a drawer of cut keys by reading each blade's tooth depths and writing them down in a fixed order. Two keys stamped with rival brand names but the same depth code fall into one envelope. The code does the matching, not the eye.

The Code

def group_anagrams(words):
    groups = {}
    for w in words:
        key = "".join(sorted(w))              # canonical signature
        groups.setdefault(key, []).append(w)  # bucket by signature
    return list(groups.values())

print(group_anagrams(["listen", "silent", "enlist", "google"]))
# [['listen', 'silent', 'enlist'], ['google']]

Your turn

What does this print?

groups = {}
for w in ["bat", "tab", "cat"]:
  k = "".join(sorted(w))
  groups.setdefault(k, []).append(w)
print(len(groups), len(groups["abt"]))

Mini quiz

1 / 3

What makes a good grouping key for anagrams?