Skip to content
mlmentorship

Group Anagrams

Use complete character counts as immutable bucket keys, preserve duplicates and input order, and change the alphabet or returned evidence explicitly.

Published · 22 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

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

ML breadth · closed-book attempt

Group Anagrams

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

Problem

Input. A list words containing only lowercase ASCII letters a through z in each string. Output. Return groups of anagrams: words with identical character counts, regardless of character order. Rules. Preserve every occurrence, including repeated words and empty strings. The reference orders groups by first appearance and words within each group by input order. Leave the input unchanged. An empty list returns []; other alphabets require the variant below. Example. ["eat", "tea", "tan", "ate", "nat", "bat"] returns [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]. Each first-group word has one a, one e, and one t.

08:00recommended time

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

30-second answer map

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

Problem trace

Separate full alphabet example: freeze fresh counts into a bucket key

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
eat[0]
0
example
words = ["eat", "tea", "tan"]
counts
a0 e0 t0; every other letter 0

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.
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.
Check: Why do eat and tea share a bucket while tan does not, despite all three words having length three?
Full interview answer 22 min read

Group input words together when each group contains exactly the same letters with the same multiplicities.

Problem

Input. A list words containing only lowercase ASCII letters a through z in each string.

Output. Return groups of anagrams: words with identical character counts, regardless of character order.

Rules. Preserve every occurrence, including repeated words and empty strings. The reference orders groups by first appearance and words within each group by input order. Leave the input unchanged. An empty list returns []; other alphabets require the variant below.

Example. ["eat", "tea", "tan", "ate", "nat", "bat"] returns [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]. Each first-group word has one a, one e, and one t.

Picture

Exact character counts decide anagram equality. Here, the same counts address a dictionary bucket.

WordNonzero slotsBucket after append
eata:1, e:1, t:1[eat]
teaa:1, e:1, t:1[eat, tea]
tana:1, n:1, t:1[tan]

Each word starts with fresh counts = [0] * 26. ord(char) - ord("a") selects its letter’s slot.

After counting, tuple(counts) freezes all 26 slots, including zeros. The table omits zero slots only to save space.

Two permitted words have equal tuples exactly when every letter has equal multiplicity.

Appending word to groups[tuple(counts)] preserves each occurrence in its correct bucket.

Dictionary lookup compares complete keys, not raw hash integers. Hash collisions do not establish key equality.

Empty words share the all-zero key. aab and abb have equal lengths and character sets, but different keys.

The trace’s | cells separate words. They are not counted characters.

Problem trace

Count each word afresh, freeze the complete key, and append every occurrence

Count each word afresh, freeze the complete key, and append every occurrenceFresh character counts describe one word, not the consumed prefix. Freeze all twenty-six slots, including zeros, into an exact dictionary key. Here ab, ba and repeated ab share one bucket; aab and abb differ despite equal lengths and character sets. Empty words share the zero key. Append every occurrence in input order. Hash collisions do not establish key equality. Different alphabets require a different key; normalization changes equality too.Fresh complete counts choose abucket; every occurrence appendsShow a and b counts. All othertwenty-four slots stay zero in thisinput and remain part of eachcomplete key.Input index 0: abaacount 1bbcount 1Bucket A: abInput index 1: baaacount 1bbcount 1Bucket A: ab, baInput index 2: aabaaacount 2bbcount 1Bucket B: aabInput index 3: abbaacount 1bbbcount 2Bucket C: abbInput index 4: abaacount 1bbcount 1Bucket A: ab, ba, abInput index 5: empty texta-count 0b-count 0Bucket D: emptyInput index 6: empty texta-count 0b-count 0Bucket D: empty, emptySeven occurrences survive in fourbuckets. First appearance ordersbuckets; input order orders eachbucket.Index output uses the same keys:zero, one, four together; two alone;three alone; five and six together.Exact full keys decide equality, notraw hash integers. Outside thelowercase contract, Python Z canaddress the t slot through negativeindexing. Change the key beforechanging alphabets.Expected work counts characters andtwenty-six slots per word. Store keysper bucket and every occurrencereference; do not replace outputlists with sets.
Read it this way: Fresh character counts describe one word, not the consumed prefix. Freeze all twenty-six slots, including zeros, into an exact dictionary key. Here ab, ba and repeated ab share one bucket; aab and abb differ despite equal lengths and character sets. Empty words share the zero key. Append every occurrence in input order. Hash collisions do not establish key equality. Different alphabets require a different key; normalization changes equality too. Would equal lengths merge aab and abb?
Reference drawing

Problem trace

Count each word afresh, freeze the complete key, and append every occurrence

Count each word afresh, freeze the complete key, and append every occurrenceFresh character counts describe one word, not the consumed prefix. Freeze all twenty-six slots, including zeros, into an exact dictionary key. Here ab, ba and repeated ab share one bucket; aab and abb differ despite equal lengths and character sets. Empty words share the zero key. Append every occurrence in input order. Hash collisions do not establish key equality. Different alphabets require a different key; normalization changes equality too.Fresh complete counts choose abucket; every occurrence appendsShow a and b counts. All othertwenty-four slots stay zero in thisinput and remain part of eachcomplete key.Input index 0: abaacount 1bbcount 1Bucket A: abInput index 1: baaacount 1bbcount 1Bucket A: ab, baInput index 2: aabaaacount 2bbcount 1Bucket B: aabInput index 3: abbaacount 1bbbcount 2Bucket C: abbInput index 4: abaacount 1bbcount 1Bucket A: ab, ba, abInput index 5: empty texta-count 0b-count 0Bucket D: emptyInput index 6: empty texta-count 0b-count 0Bucket D: empty, emptySeven occurrences survive in fourbuckets. First appearance ordersbuckets; input order orders eachbucket.Index output uses the same keys:zero, one, four together; two alone;three alone; five and six together.Exact full keys decide equality, notraw hash integers. Outside thelowercase contract, Python Z canaddress the t slot through negativeindexing. Change the key beforechanging alphabets.Expected work counts characters andtwenty-six slots per word. Store keysper bucket and every occurrencereference; do not replace outputlists with sets.
Execution trace
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
eat[0]
0
example
words = ["eat", "tea", "tan"]
counts
a0 e0 t0; every other letter 0

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.
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.
Check: Why do eat and tea share a bucket while tan does not, despite all three words having length three?
Read it this way: Fresh character counts describe one word, not the consumed prefix. Freeze all twenty-six slots, including zeros, into an exact dictionary key. Here ab, ba and repeated ab share one bucket; aab and abb differ despite equal lengths and character sets. Empty words share the zero key. Append every occurrence in input order. Hash collisions do not establish key equality. Different alphabets require a different key; normalization changes equality too. Would equal lengths merge aab and abb?

Code

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())

Let count words, count characters, and count groups. Expected work is under constant-cost integer operations. Keys store counts, and buckets retain references to existing words.

The alphabet boundary matters. Python accepts negative indices: Z selects slot -7, which is the t slot.

Change the Key or the Evidence

Start from group_anagrams. Two adjustable parts are the equivalence key and bucket contents.

  1. Allow arbitrary Python characters.

    New task: Remove the lowercase-ASCII restriction without changing exact character equality.

    Picture and change: Replace the 26 counts with a sorted tuple of all characters. Keep dictionary buckets and append original words.

    Code: Complete replacement:

    def group_anagrams_any(words):
       groups = {}
       for word in words:
          key = tuple(sorted(word))
          groups.setdefault(key, []).append(word)
       return list(groups.values())

    Check: ["Aa","aA","aa"] becomes [["Aa","aA"],["aa"]]. Two empty words remain together.

    Sorting code points does not normalize case or composed/decomposed spellings. Expected work is , where each is a word length. Keys and output use references.

    Use when: The input alphabet changes. A normalization policy would change equality too, so specify it separately.

  2. Return original indices.

    New task: Locate each anagram occurrence in the input.

    Picture and change: Keep fresh lowercase counts and the exact tuple key. Replace appended words with their indices.

    Code: Complete replacement under the original alphabet contract:

    def group_anagram_indices(words):
       groups = {}
       for index, word in enumerate(words):
          counts = [0] * 26
          for char in word:
             counts[ord(char) - ord("a")] += 1
          groups.setdefault(tuple(counts), []).append(index)
       return list(groups.values())

    Check: ["eat","tea","eat","tan"] returns [[0,1,2],[3]]. Both eat positions survive.

    The tuple still decides membership. Time and entry counts match the reference.

    Use when: Callers need original-position evidence rather than word references.

Rebuild the Key

Why must counts reset for every word? Would equal lengths or equal character sets suffice?

Answer: Each key must describe one word, not the consumed prefix. Neither length nor a set distinguishes aab from abb.

Mutable lists cannot be dictionary keys. Hashing a tuple is not permission to replace it with its hash integer.