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?
Sources and provenance
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.
Word
Nonzero slots
Bucket after append
eat
a:1, e:1, t:1
[eat]
tea
a:1, e:1, t:1
[eat, tea]
tan
a: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
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
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
Count e in eatThe character e increments slot ord("e")-ord("a") from 0 to 1.
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 defaultdictdef 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 n count words, L count characters, and g count groups.
Expected work is O(L+26n) under constant-cost integer operations.
Keys store O(26g) counts, and buckets retain O(n) 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.
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 O(n+∑mlog(m+1)), where each m is a word length.
Keys and output use O(L+n) references.
Use when: The input alphabet changes. A normalization policy would change equality too, so specify it separately.
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.