Skip to content
mlmentorship

Group Anagrams

Put words with the same letters into the same group.

Published · 9 min read ·Core ·Foundation

30-second answer map

Visual first · depth when needed

Use each word's 26-letter frequency tuple as its bucket address.

Preparing the visual…

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

How practice works

ML breadth · closed-book attempt

Group Anagrams

Explain the mechanism, why it works, when it fails, and one alternative.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

Put words with the same letters into the same group.

Start with the concrete trace below. It shows the state the algorithm must carry as it runs.

Problem trace

Group Anagrams: Use each word's 26-letter frequency tuple as its bucket address.

Input and goalPut words with the same letters into the same group.
Initialize the group mapThe map is empty and the fresh 26-count array for "eat" is all zeros.
eat[0]e0a1t2|3t4e5a6|7t8a9n10
examplewords = ["eat", "tea", "tan"]mapLabel26-count tuple -> bucketcountsa0 e0 t0; every other letter 0
26-count tuple -> bucketempty

Recognize it
Many lowercase words must be partitioned by equal letter multiplicities while their original letter order is irrelevant.
Keep true
After each word, every processed word appears once in the bucket keyed by its exact 26-count tuple; two words share a bucket exactly when they are anagrams.
Reuse it
Canonicalize each item into an equality-preserving key, then group by that key; this transfers to shifted-string groups, normalized records, and equivalence-class indexing.
Read it this way: The map is empty and the fresh 26-count array for "eat" is all zeros. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.

Pattern: Hash map with a shared key.

Simple idea: Count each lowercase letter. Anagrams have the same 26 counts, so they use the same tuple as a map key.

from collections import defaultdict

def group_anagrams(words: list[str]) -> list[list[str]]:
   groups: dict[tuple[int, ...], list[str]] = defaultdict(list)
   for word in words:
      counts = [0] * 26
      for char in word:
         counts[ord(char) - ord("a")] += 1
      groups[tuple(counts)].append(word)
   return list(groups.values())

Cost: time and space for words of average length .