Partition Words Into Anagram Buckets
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement group_anagrams(strs: List[str]) -> List[List[str]], which partitions a list of lowercase English words strs into buckets of mutual anagrams.
Two strings belong in the same bucket if and only if every character from 'a' through 'z' appears with identical multiplicity in both strings (equivalently, one string can be obtained by permuting all characters of the other).
- Keep repeated occurrences of the same string as separate elements inside their shared bucket.
- Order the returned buckets by the index at which each bucket's first member appears in
strs, and keep strings inside every bucket in their original left-to-right input order. - If
strsis empty, return[].
Examples
Example 1
Input: strs = ["loop", "polo", "note", "pool", "tone", "lamp"]
Output: [["loop", "polo", "pool"], ["note", "tone"], ["lamp"]]
Explanation: "loop", "polo", and "pool" each contain one 'l', two 'o's, and one 'p'. "note" and "tone" each contain 'e', 'n', 'o', and 't' once. "lamp" shares its character counts with no other word, forming its own single-item bucket.
Example 2
Input: strs = ["", "odin", "", "dion"]
Output: [["", ""], ["odin", "dion"]]
Explanation: Both empty strings have zero occurrences of every letter and land together in the first bucket; "odin" and "dion" share one 'd', 'i', 'n', and 'o' and form the second bucket.
Constraints
1 <= len(strs) <= 10^4(an empty list[]should also return[])0 <= len(strs[i]) <= 100- Every character in
strs[i]is a lowercase ASCII letter ('a'–'z').
Step-by-step walkthrough
Understand the goal and output ordering
We are given a list of lowercase English words
strsand want to collect mutual anagrams (strings built from the exact same characters with the exact same repeat counts) into shared buckets. For example,"loop","polo", and"pool"are anagrams (1 'l',2 'o's,1 'p'), whereas"aab"and"abb"are not (2 'a's vs1 'a'), and repeated words like["ab", "ab"]stay as separate entries inside their shared bucket.Notice the ordering rule: buckets appear in order of their first member in
strs, and words inside each bucket preserve their left-to-right input order (for Example 1,[["loop", "polo", "pool"], ["note", "tone"], ["lamp"]]). Scanningstrsleft to right and appending into a standard Python dictionary gives this exact order automatically.Why comparing words against every bucket is too slow
A naive approach maintains a list of buckets and compares each incoming word against the first word of every bucket created so far.
When
strsholdsN = 10,000distinct non-anagram words: - Word 1 checks0buckets, Word 2 checks1bucket, ..., WordNchecksN - 1buckets. - Across the full list, that performsN * (N - 1) / 2—roughly50,000,000word comparisons—each inspecting up toK = 100characters!Instead of comparing words pairwise, we want an independent summary label computed from each word by itself so matching words jump straight to the same bucket.
Key idea: turn each word into a 26-letter frequency signature
Assign every word a canonical signature (a standardized representation that is equal for two words if and only if they have identical letter counts), and store buckets in a hash map (Python's
dict, which finds or inserts a key inO(1)average time).Two classic signatures work well: 1. Sorted characters (
"".join(sorted(word))):"loop","polo", and"pool"all sort to"loop"inO(K log K)time per word. 2. 26-letter count tuple: Because inputs only contain'a'through'z', we count occurrences of all26letters in oneO(K)pass:index: 0 ... 11 ... 14 15 ... 25 letter: 'a' ... 'l' ... 'o' 'p' ... 'z' "loop" -> ( 0, ..., 1, ..., 2, 1, ..., 0 ) --+ "polo" -> ( 0, ..., 1, ..., 2, 1, ..., 0 ) --+--> identical 26-int tuple! "pool" -> ( 0, ..., 1, ..., 2, 1, ..., 0 ) --+ "note" -> ( 0, ..., 0, ..., 1, 0, ..., 0 ) -----> different tuple (has 'e','n','t')Two small rules keep this count key bug-free: - Convert the list to a
tuple: Python lists can be mutated in place, so using alistas a dictionary key raisesTypeError: unhashable type: 'list'. Tuples are immutable, sotuple(letter_counts)hashes cleanly. - Keep the 26 numbers in separate slots (never glue them into an undelimited string): Joining counts via"".join(map(str, counts))collapses both1 'a' + 11 'b's("1" + "11") and11 'a's + 1 'b'("11" + "1") into"111..."! Separate tuple slots(1, 11, ...)vs(11, 1, ...)never collide.Write the helper to compute a word's signature
In ASCII, lowercase
'a'through'z'occupy consecutive codes (ord('a') == 97up toord('z') == 122). Subtractingord('a')maps'a'to index0,'b'to index1, ..., and'z'to index25. An empty string""does zero loop iterations and returns26zeros, placing all empty strings into the same bucket.def build_anagram_signature(word: str) -> Tuple[int, ...]: # letter_counts: 26-slot frequency table for 'a'..'z', e.g. "loop" -> [..., l:1, ..., o:2, p:1, ...] letter_counts = [0] * 26 for ch in word: alphabet_index = ord(ch) - ord("a") letter_counts[alphabet_index] += 1 # Convert mutable list to an immutable tuple so Python allows it as a dictionary key. return tuple(letter_counts)Group words in one pass with a dictionary
Walk through
strsonce from left to right. Compute each word's 26-integersignature; initialize an empty bucket the first time a signature appears, and appendword. Because Python dictionaries preserve key insertion order,list(groups_by_signature.values())returns all buckets in first-seen order.def group_anagrams(strs: List[str]) -> List[List[str]]: # groups_by_signature: maps 26-int count tuple -> list of words sharing that signature. # Python dicts preserve insertion order, keeping groups in first-seen order and words in input order. groups_by_signature: Dict[Tuple[int, ...], List[str]] = {} for word in strs: signature = build_anagram_signature(word) if signature not in groups_by_signature: groups_by_signature[signature] = [] groups_by_signature[signature].append(word) return list(groups_by_signature.values())Trace through Example 1 step by step
Let's watch
groups_by_signatureevolve on["loop", "polo", "note", "pool", "tone", "lamp"](writing only non-zero entries of each 26-int tuple for clarity):1. "loop" -> key (l:1, o:2, p:1) [new] -> { (l:1,o:2,p:1): ["loop"] } 2. "polo" -> key (l:1, o:2, p:1) [hit] -> { (l:1,o:2,p:1): ["loop", "polo"] } 3. "note" -> key (e:1, n:1, o:1, t:1) [new] -> { (l:1,o:2,p:1): ["loop", "polo"], (e:1,n:1,o:1,t:1): ["note"] } 4. "pool" -> key (l:1, o:2, p:1) [hit] -> { (l:1,o:2,p:1): ["loop", "polo", "pool"], (e:1,n:1,o:1,t:1): ["note"] } 5. "tone" -> key (e:1, n:1, o:1, t:1) [hit] -> { (l:1,o:2,p:1): ["loop", "polo", "pool"], (e:1,n:1,o:1,t:1): ["note", "tone"] } 6. "lamp" -> key (a:1, l:1, m:1, p:1) [new] -> { (l:1,o:2,p:1): ["loop", "polo", "pool"], (e:1,n:1,o:1,t:1): ["note", "tone"], (a:1,l:1,m:1,p:1): ["lamp"] } groups_by_signature.values() -> [["loop", "polo", "pool"], ["note", "tone"], ["lamp"]]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def build_anagram_signature(word: str) -> Tuple[int, ...]: # letter_counts: 26-slot frequency table for 'a'..'z', e.g. "loop" -> [..., l:1, ..., o:2, p:1, ...] letter_counts = [0] * 26 for ch in word: alphabet_index = ord(ch) - ord("a") letter_counts[alphabet_index] += 1 # Convert mutable list to an immutable tuple so Python allows it as a dictionary key. return tuple(letter_counts) def group_anagrams(strs: List[str]) -> List[List[str]]: # groups_by_signature: maps 26-int count tuple -> list of words sharing that signature. # Python dicts preserve insertion order, keeping groups in first-seen order and words in input order. groups_by_signature: Dict[Tuple[int, ...], List[str]] = {} for word in strs: signature = build_anagram_signature(word) if signature not in groups_by_signature: groups_by_signature[signature] = [] groups_by_signature[signature].append(word) return list(groups_by_signature.values())✅ Submit now — all tests should pass.
Intuition & how it works
Imagine sorting pouches of letter tiles into matching bins without dumping two pouches out side by side to compare them. Instead, you count how many 'a' tiles, 'b' tiles, ..., 'z' tiles sit inside each pouch and write that 26-number tally on a label—its canonical signature (a standardized key computed from one item alone so that two items match if and only if their keys are identical). You then drop each pouch into the bin for that label using a hash map (Python's dict, a key-value lookup table that finds or inserts a key in O(1) average time). Mutual anagrams (words built from the exact same letters with the exact same multiplicities, such as "loop" and "polo") produce the exact same 26-number label and land in the same bin automatically.
Comparing each incoming word against every existing bucket takes roughly N^2 / 2 = 50,000,000 word comparisons when N = 10,000 words are all distinct, with each comparison scanning up to 100 characters. Computing one 26-slot frequency tuple per word replaces all pairwise scans with a single O(1) dictionary lookup per word.
Walk through ["loop", "polo", "note", "pool"] (showing only non-zero entries of each 26-int tuple):
1. "loop" yields (l:1, o:2, p:1), creating the first bucket (l:1, o:2, p:1) -> ["loop"].
2. "polo" yields the same tuple (l:1, o:2, p:1), hitting that bucket and updating it to ["loop", "polo"].
3. "note" yields (e:1, n:1, o:1, t:1), opening a second bucket ["note"].
4. "pool" yields (l:1, o:2, p:1), appending to the first bucket to produce [["loop", "polo", "pool"], ["note"]].
Complexity
Let N be the number of strings in strs and K be the average length of a string.
- Time: O(N * K) (specifically
O(N * (K + 26)), where26is the fixed alphabet size). For each of theNwords, we scan itsKcharacters once to tally counts, spend26constant steps converting and hashing the 26-integer tuple, and perform anO(1)average-time dictionary lookup and list append. - Space: O(N) auxiliary reference space (specifically
O(G * 26 + N), whereG <= Nis the number of distinct anagram buckets, orO(N * K)when counting the character payloads of allNstrings). Each bucket stores one 26-integer tuple key in the dictionary, and the bucket lists holdNreferences to the original strings without copying their characters.
Edge cases
- Empty input list (
[]): The loop executes zero times and returns[]. - Empty strings (
["", "odin", "", "dion"]): Every""produces the all-zero 26-tuple(0, 0, ..., 0), grouping all empty strings together ([["", ""], ["odin", "dion"]]). - Duplicate words (
["ab", "ba", "ab"]): Identical strings share the same signature and stay once per occurrence in their bucket ([["ab", "ba", "ab"]]). - Same unique letters, different multiplicities (
"aab"vs"abb"):"aab"has(a:2, b:1, ...)whereas"abb"has(a:1, b:2, ...), keeping them in distinct buckets. - Multi-digit counts (
"a" + "b" * 11vs"a" * 11 + "b"): Because counts occupy separate tuple positions(1, 11, ...)vs(11, 1, ...), double-digit frequencies up to100never collide. - All unique vs all anagrams: Handles
Nsingleton buckets and1bucket of sizeNequally well in linear time while preserving first-seen order.
Common mistakes
- Using a
listdirectly as a dictionary key: Lists are mutable (their contents can be modified after creation), so Python raisesTypeError: unhashable type: 'list'. Always wrapletter_countsin an immutable (unchangeable)tuple. - Joining counts into a string without delimiters: Writing
"".join(str(c) for c in counts)turns both(1, 11, 0, ...)and(11, 1, 0, ...)into"1110...", merging non-anagrams. Usetuple(counts)instead. - Using
frozenset(word)as the key: Sets discard repeat counts, falsely grouping"loop"(o:2) with"lop"(o:1). - Summing or XORing character codes:
"ad"(97 + 100 = 197) and"bc"(98 + 99 = 197) share the same ASCII sum without being anagrams. Multiplying the first 26 primes avoids collisions mathematically, but overflows 64-bit integers in C++/Java/Rust on 100-letter words (101^100 >> 2^64). - Passing uppercase or non-ASCII text into
ord(ch) - ord('a'): For'Z',ord('Z') - ord('a')is-7, and Python's negative indexing silently increments slot19('t'), grouping"Z"with"t"! Only use a 26-slot offset array when inputs are guaranteed to be'a'–'z'. - Pairwise bucket scanning (
O(N^2 * K)): Comparing every word against existing buckets times out whenN = 10^4.
Follow-up questions
- How would you build the canonical key if inputs could contain arbitrary Unicode text rather than only ASCII 'a' through 'z'? Because Unicode defines over
140,000characters rather than26, replace the fixed 26-slot table with either"".join(sorted(word))(O(K log K)per word) or a sparse frequency mapcollections.Counter(word)converted intotuple(sorted(counter.items())). Before counting, apply Unicode normalization (unicodedata.normalize("NFC", word)—converting equivalent encodings, such as precomposed'é'vs'e'plus a combining acute accent, into one standard form) so visually identical characters match and combining marks cannot detach and swap across base letters. If multi-code-point emoji or accented clusters must move as indivisible units, segment each string into grapheme clusters (user-perceived characters) first. - How do the runtime and memory footprints compare between the 26-count tuple key and sorting each word of average length K across N words? The 26-integer count tuple runs in
O(N * K)time (treating the alphabet size26as a constant) and usesO(G)key space (26integers for each ofG <= Ndistinct groups, independent ofK) plusO(N)string references. Sorting each word via"".join(sorted(word))takesO(N * K log K)time andO(G * K)key space because every distinct bucket stores a sorted copy of lengthK—making the 26-tuple asymptotically faster and leaner whenKgrows large, while for short strings (K <= 100) Python's C-implementedsorted()(Timsort) has very small constant factors. - How would you group all anagrams when the dataset is hundreds of gigabytes on disk and cannot fit into RAM at once? Use two-pass external hash partitioning (sharding an out-of-core dataset across
Ptemporary disk files via a deterministic hash so identical signatures always land in the same shard). In Pass 1, stream words sequentially from disk, compute each word's canonical signature, hash that signature with a deterministic function likehashlib.blake2b(avoiding Python's saltedhash()), and append(signature, word)to sharddigest % P, pickingPlarge enough that every shard fits comfortably in RAM. In Pass 2, load one shard at a time into memory, run our in-memory dictionary grouping on that shard, and flush its finished buckets to output storage (or run a distributedGROUP BY signatureshuffle in Spark).
Alternative approaches
- Sorted-characters key (
"".join(sorted(word))): Concise and alphabet-agnostic inO(N * K log K)time. ForK <= 100, C-levelTimsortruns nearly as fast in Python as a 26-element bytecode loop. collections.defaultdict(list): Eliminates theif signature not in groups_by_signature:check viagroups_by_signature[signature].append(word), keeping the exact sameO(N * K)complexity and insertion-order behavior.
Follow-up questions
- How would you build the canonical key if inputs could contain arbitrary Unicode text rather than only ASCII 'a' through 'z'?
- How do the runtime and memory footprints compare between the 26-count tuple key and sorting each word of average length K across N words?
- How would you group all anagrams when the dataset is hundreds of gigabytes on disk and cannot fit into RAM at once?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array