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 strs is 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

  1. Understand the goal and output ordering

    We are given a list of lowercase English words strs and 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 vs 1 '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"]]). Scanning strs left to right and appending into a standard Python dictionary gives this exact order automatically.

  2. 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 strs holds N = 10,000 distinct non-anagram words: - Word 1 checks 0 buckets, Word 2 checks 1 bucket, ..., Word N checks N - 1 buckets. - Across the full list, that performs N * (N - 1) / 2—roughly 50,000,000 word comparisons—each inspecting up to K = 100 characters!

    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.

  3. 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 in O(1) average time).

    Two classic signatures work well: 1. Sorted characters ("".join(sorted(word))): "loop", "polo", and "pool" all sort to "loop" in O(K log K) time per word. 2. 26-letter count tuple: Because inputs only contain 'a' through 'z', we count occurrences of all 26 letters in one O(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 a list as a dictionary key raises TypeError: unhashable type: 'list'. Tuples are immutable, so tuple(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 both 1 'a' + 11 'b's ("1" + "11") and 11 'a's + 1 'b' ("11" + "1") into "111..."! Separate tuple slots (1, 11, ...) vs (11, 1, ...) never collide.

  4. Write the helper to compute a word's signature

    In ASCII, lowercase 'a' through 'z' occupy consecutive codes (ord('a') == 97 up to ord('z') == 122). Subtracting ord('a') maps 'a' to index 0, 'b' to index 1, ..., and 'z' to index 25. An empty string "" does zero loop iterations and returns 26 zeros, 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)
    
  5. Group words in one pass with a dictionary

    Walk through strs once from left to right. Compute each word's 26-integer signature; initialize an empty bucket the first time a signature appears, and append word. 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())
    
  6. Trace through Example 1 step by step

    Let's watch groups_by_signature evolve 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"]]
    
  7. 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)), where 26 is the fixed alphabet size). For each of the N words, we scan its K characters once to tally counts, spend 26 constant steps converting and hashing the 26-integer tuple, and perform an O(1) average-time dictionary lookup and list append.
  • Space: O(N) auxiliary reference space (specifically O(G * 26 + N), where G <= N is the number of distinct anagram buckets, or O(N * K) when counting the character payloads of all N strings). Each bucket stores one 26-integer tuple key in the dictionary, and the bucket lists hold N references 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" * 11 vs "a" * 11 + "b"): Because counts occupy separate tuple positions (1, 11, ...) vs (11, 1, ...), double-digit frequencies up to 100 never collide.
  • All unique vs all anagrams: Handles N singleton buckets and 1 bucket of size N equally well in linear time while preserving first-seen order.

Common mistakes

  • Using a list directly as a dictionary key: Lists are mutable (their contents can be modified after creation), so Python raises TypeError: unhashable type: 'list'. Always wrap letter_counts in 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. Use tuple(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 slot 19 ('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 when N = 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,000 characters rather than 26, replace the fixed 26-slot table with either "".join(sorted(word)) (O(K log K) per word) or a sparse frequency map collections.Counter(word) converted into tuple(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 size 26 as a constant) and uses O(G) key space (26 integers for each of G <= N distinct groups, independent of K) plus O(N) string references. Sorting each word via "".join(sorted(word)) takes O(N * K log K) time and O(G * K) key space because every distinct bucket stores a sorted copy of length K—making the 26-tuple asymptotically faster and leaner when K grows large, while for short strings (K <= 100) Python's C-implemented sorted() (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 P temporary 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 like hashlib.blake2b (avoiding Python's salted hash()), and append (signature, word) to shard digest % P, picking P large 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 distributed GROUP BY signature shuffle in Spark).

Alternative approaches

  • Sorted-characters key ("".join(sorted(word))): Concise and alphabet-agnostic in O(N * K log K) time. For K <= 100, C-level Timsort runs nearly as fast in Python as a 26-element bytecode loop.
  • collections.defaultdict(list): Eliminates the if signature not in groups_by_signature: check via groups_by_signature[signature].append(word), keeping the exact same O(N * K) complexity and insertion-order behavior.

Follow-up questions

Similar questions

More Okx interview questions

All 1 Okx questions →