Skip to content
GKgkml.dev
← Problem set
#49MediumArrays & hashing

Group Anagrams

The tell: Group items that share a property — so you need a canonical key for that property.

How you get there

  1. 1Anagrams share a sorted spelling, so the sorted tuple is a canonical key.
  2. 2A defaultdict(list) buckets each word under its key in one pass.
  3. 3A 26-length count tuple is a faster key than sorting when words are long.

Solution

Python
from collections import defaultdict

def group_anagrams(strs: list[str]) -> list[list[str]]:
    groups: dict[tuple, list[str]] = defaultdict(list)
    for word in strs:
        counts = [0] * 26
        for ch in word:
            counts[ord(ch) - ord('a')] += 1
        groups[tuple(counts)].append(word)   # tuple is hashable, list is not
    return list(groups.values())
Time
O(n · k log k) for k-length words
Space
O(n · k)

What goes wrong

Using a list as the dict key raises TypeError — it must be converted to a tuple.