Forward Deployed EngineeringCodingHash Maps and Strings

Group anagrams: cluster a list of strings into anagram groups

Question 34 of 73 · Updated

On this page

Interview-ready answer#

I would group the strings using a hash map whose key is a canonical representation of each string's character multiset. Two strings belong to the same anagram group if and only if they contain exactly the same characters with exactly the same multiplicities, regardless of their order.

The simplest implementation sorts the characters of each word and uses the resulting string as the dictionary key. For example, "eat", "tea" and "ate" all produce the key "aet". For n strings of maximum length k, this takes O(nk log k) time under the usual comparison-sorting and hash-table assumptions, with additional space for canonical keys and groups.

If the input is restricted to lowercase English letters a–z, I can avoid sorting by counting each character in a 26-element array and converting it into an immutable tuple. The fixed-alphabet approach takes expected O(n(k + 26)) time, usually simplified to O(nk) for nonempty strings and a constant-size alphabet. For arbitrary Unicode code points, I would use a sorted string or a hashable collection of character/count pairs instead of assuming a 26-letter alphabet.

Both approaches preserve duplicates and return the original strings. I would clarify case sensitivity, Unicode normalization and output ordering before implementing the solution.

1. Understand the problem contract#

Given a list of strings, partition it into groups such that every input occurrence appears in exactly one group, and two occurrences are in the same group exactly when their strings are anagrams.

For the classic interview problem, strings usually contain lowercase English letters and the order of groups and elements is not prescribed. The first and third implementations below additionally support arbitrary Python strings with exact code-point equality.

Example:

  • Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
  • One valid output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]

Anagrams are not merely strings with the same set of characters. "aab" and "abb" contain the same distinct letters but have different character counts, so they are not anagrams.

The canonical key is an internal identifier, not the output. Return each original word, including repeated identical words. Do not replace the group with a deduplicated set or a sorted representation of its members.

Why a hash map?#

A naive approach might compare every word against a representative of every existing group. In the worst case, when no two words are anagrams, it performs a quadratic number of comparisons in the number of words. Computing one canonical key per word converts the problem into exact-key grouping.

The key must capture the complete character multiset. Summing character codes is insufficient because distinct strings can have the same sum. Multiplying character codes or using a single rolling hash without collision verification is also not a reliable equivalence test.

Python dictionaries handle ordinary hash collisions by checking key equality. Correctness depends on the equality of the complete canonical keys, not on assuming their hashes never collide.

2. Approach A: sorting-based canonical keys#

Sort each string's characters, join them into an immutable string and append the original word to the dictionary bucket for that key.

PYTHON
from collections import defaultdict def group_sorted(words): groups = defaultdict(list) for word in words: key = ''.join(sorted(word)) groups[key].append(word) return list(groups.values())

Dry run#

WordSorted keyDictionary change
eataetCreate aet: [eat]
teaaetAppend tea to aet
tanantCreate ant: [tan]
ateaetAppend ate to aet
natantAppend nat to ant
batabtCreate abt: [bat]

The dictionary now contains three keys: aet, ant and abt. Its values are the requested groups.

Loading diagram…

For an empty input, the loop is skipped and the function returns an empty list.

Correctness proof#

Let S(w) denote the sorted sequence of characters of string w.

If two words are anagrams, their character multiplicities are identical. Sorting both words places the same characters in the same canonical order, so S(a) = S(b).

Conversely, if S(a) = S(b), both sorted sequences contain exactly the same characters with the same multiplicities. Therefore a and b are anagrams.

The dictionary groups words by equality of S(w), so all words in each group are anagrams and every pair of anagrams maps to the same group. The loop appends every input occurrence once. This proves that the algorithm produces the required partition and preserves duplicates.

Complexity#

Let n be the number of strings, L the total number of code points, k the maximum length, and the length of the i-th string.

  • Sorting and constructing keys costs O(n + sum of log( + 1)) in the worst case under the conventional unit-cost comparison model. This includes empty and one-character words.
  • Dictionary operations add expected work proportional to the total key lengths and number of words. A conventional simplified bound is O(n + nk log(k + 1)).
  • Stored canonical keys may contain O(L) characters in total in the worst case; group lists retain O(n) references.
  • The sorting temporary space for one word is O(k), in addition to retained keys and group storage.

The implementation does not copy the original string contents into new output strings. The returned lists reference the original immutable strings. The analysis includes output references and distinguishes them from temporary storage.

3. Approach B: fixed-alphabet frequency vectors#

For lowercase ASCII letters, use a count vector with one position per letter. At position i, store the number of occurrences of the character chr(ord('a') + i).

For "eat" and "tea", the count for a is one, e is one, t is one, and all other positions are zero. Both strings therefore produce an identical vector without sorting.

PYTHON
from collections import defaultdict def group_counts(words): groups = defaultdict(list) for word in words: counts = [0] * 26 for ch in word: i = ord(ch) - ord('a') if not 0 <= i < 26: raise ValueError('expected lowercase ASCII a-z') counts[i] += 1 groups[tuple(counts)].append(word) return list(groups.values())

A Python list is mutable and cannot serve as a dictionary key. Converting the list into a tuple produces an immutable, hashable key. Checking that the index is in range is important: negative list indices are valid in Python and can otherwise silently count invalid characters in the wrong positions.

Dry run#

The following table displays only nonzero counts; the actual key is always a 26-element tuple, including zeros.

WordNonzero countsGroup
eata:1, e:1, t:11
teaa:1, e:1, t:11
tana:1, n:1, t:12
atea:1, e:1, t:11
nata:1, n:1, t:12
bata:1, b:1, t:13

Correctness proof#

Define F(w)[i] as the count of letter i in w. If two strings are anagrams, every letter count is equal, so their count tuples are equal. If their tuples are equal, the count of every allowed character is identical, so they are anagrams.

The tuple captures exactly the complete multiset under the specified alphabet. Grouping by this key is therefore sound and complete. As with sorting, each input occurrence is appended exactly once.

Complexity#

For an alphabet of size A:

  • Counting characters takes O(L).
  • Initializing, converting and hashing frequency vectors takes O(nA).
  • Expected total time is O(L + nA), assuming ordinary hash-table behavior and unit-cost character indexing and count arithmetic.
  • Retaining g distinct keys takes O(gA) space, where g is the number of groups. The output stores O(n) references and a temporary count vector requires O(A) space.

For fixed A = 26, expected time is O(L + n), and retained dictionary and grouping space is O(n). In terms of maximum length k, the time is O(n(k + 1)), commonly written O(nk) when k is at least one. For a very large or sparse alphabet, a dense frequency vector can waste memory and time.

4. Approach C: arbitrary character-frequency keys#

A sparse frequency map is useful when strings are not restricted to lowercase English letters.

PYTHON
from collections import defaultdict, Counter def group_unicode(words): groups = defaultdict(list) for word in words: groups[frozenset(Counter(word).items())].append(word) return list(groups.values())

Counter produces a mapping from character to positive count. Its items are pairs such as ('a', 2). A frozenset of those pairs is immutable, hashable and independent of the insertion order of the characters.

Using tuple(Counter(word).items()) without sorting is not generally correct: the items may be ordered by first occurrence, so two anagrams can yield different tuples. Sorting the items before constructing a tuple is another valid implementation, though it adds sorting work over the distinct characters.

Let be the number of distinct characters in word i. Counting and constructing the frozenset take expected O( + ) time under ordinary hashing assumptions. Since ≤ , the complete algorithm takes expected O(n + L) time. Retained keys use space proportional to the distinct character/count pairs in the stored groups, plus O(n) output references; the temporary counter is proportional to the distinct characters in the current word.

Python frozenset equality verifies complete pair membership, so the algorithm remains correct when ordinary hash collisions occur. Adversarial hash-table performance and arbitrary-precision count arithmetic are outside the simple expected-time bound.

5. Unicode: clarify what a character means#

Python strings are sequences of Unicode code points. These three examples illustrate why anagram equivalence must be specified rather than assumed:

Input stringsExact code-point behavior
"Ab", "bA", "ab"First two group together; lowercase ab belongs to a different group
"éa", "aé", "éa"First two group together; the third uses e plus a combining acute accent
"😀a", "a😀"Same multiset of code points; group together

The third accented spelling above may look identical to the first when rendered. Its underlying representation differs.

If the product requires canonically equivalent spellings to be treated the same, normalize each string to a specified Unicode form, such as NFC, before constructing its key. If case-insensitive matching is intended, use an explicitly defined case-folding policy and consider normalization after folding as well. Case folding can change the number of code points, as with German sharp s. Compatibility normalization such as NFKC can intentionally collapse distinctions that might matter for names or identifiers; do not introduce it silently.

If the intended unit is a user-perceived character (extended grapheme cluster), segment using a Unicode-aware grapheme segmentation implementation before counting or sorting those units. Code-point sorting alone does not implement that contract.

Unicode normalization and case policies should apply to the canonical key only if the output is expected to retain original strings. Neither normalization nor case folding is part of the three exact-match implementations in this lesson.

6. Compare the approaches#

ApproachExpected overall time under stated assumptionsSuitable inputMain trade-off
Sorted charactersO(n + sum log( + 1))Arbitrary code-point stringsSimple and easy to explain; sorting cost
Dense count tupleO(L + nA)Known small alphabetAvoids sorting; fixed vector overhead
Sparse frequency frozensetO(n + L)Arbitrary code-point stringsExpected linear counting; object and hash-map overhead

The sorting approach is often the best interview starting point because its key is intuitive and easy to validate. For a fixed alphabet with long strings, frequency vectors give a stronger asymptotic bound. For general alphabets, sparse keys avoid allocating an array covering every possible code point.

These bounds are not measured performance guarantees. Python's sorting is implemented in optimized native code, so a short-string sorting solution can outperform a Python-level loop despite the different asymptotic complexity. Benchmark representative workloads if the choice matters in production.

7. Edge cases and common mistakes#

CaseExpected behavior
[][]
["", ""]One group containing both empty strings
["a", "aa", "aaa"]Three groups
["abc", "abc", "bca"]One group containing all three occurrences
["ab", "aab"]Separate groups
["aab", "abb"]Separate groups
Uppercase, punctuation or emojiSorting and sparse count support exact matching; fixed ASCII implementation rejects invalid input

Common mistakes include using a set of letters rather than counts, using mutable lists as dictionary keys, returning canonical keys instead of original words, discarding duplicates, assuming output order is prescribed, and using the fixed-alphabet algorithm without checking the input contract.

In modern Python dictionaries preserve insertion order. The three functions therefore return groups ordered by the first appearance of their canonical key and words in their input order within each group. The classic problem accepts any group order; if a consumer requires a different deterministic ordering, document it and include the cost of additional sorting.

8. Tested implementations and verification#

All three exact implementations were executed locally with Python 3.13.5.

The exhaustive test vocabulary contained the empty string and every binary-alphabet string of lengths one through three, for a total of 15 distinct strings. The test harness enumerated every ordered input array of length zero through four over that vocabulary: 54,241 arrays.

For each array, an independent reference implementation compared each word against existing group representatives using direct character-count equality and preserved input order. Each of the three implementations returned exactly the expected groups for all 54,241 arrays.

Additional validation covered eight explicit input arrays for each of the sorting and sparse-count implementations, including the standard example, duplicate and repeated characters, empty strings, composed/decomposed accents, emoji, case sensitivity, spaces and German sharp s. Six invalid-character cases were rejected by the dense ASCII implementation.

Total validated outcomes: 162,745 (162,723 exhaustive implementation runs, 16 additional regression runs and six invalid-input checks). All passed. These tests establish correctness for the tested inputs; they do not benchmark production performance or validate a separate Unicode normalization or grapheme-cluster implementation.

9. Interviewer follow-ups#

Can we group anagrams in linear time? Yes, expected O(n + L) with a fixed small alphabet or a sparse character-frequency key under ordinary hash-table assumptions. Reading all input characters is necessary in the worst case to distinguish multisets, so this is asymptotically optimal under the conventional model.

Why can't we use set(word) as the key? It discards multiplicity. "aab" and "abb" would have the same set, but they are not anagrams.

What if the interviewer asks only whether two strings are anagrams? Compare lengths and count characters or sort both strings. You do not need to build a dictionary of groups.

What if the dataset is too large for memory? Compute a canonical key per record, partition by a stable hash of the complete key, then group within each partition or use external sorting. Do not use a truncated hash as the sole equality test. Account for skew, large groups, I/O, and any requirement to preserve order.

What if I need the number of groups only? Retain a set of canonical keys instead of lists of original words. This avoids storing group member references, though the keys themselves still consume memory.

Can I use character sums or prime products? Character sums are not injective. Exact prime products with a unique prime per allowed character can represent multiplicities by unique factorization, but arbitrary-precision products grow, fixed-width overflow can cause collisions, and the cost model changes. Count tuples or sorted keys are usually clearer and safer.

How does this relate to FDE work? It demonstrates canonicalization and exact-key grouping, which also appear in deduplication, reconciliation, normalization and record matching. In real customer data, the equivalence policy must reflect the business semantics. Anagrams are generally not a valid identity-matching rule for people, organizations or product names. Preserve provenance and original records, and do not collapse distinct entities merely because an overly broad canonical key matches.

Interview takeaway#

Use a dictionary to group by a canonical key that preserves complete character multiplicities. Sorting is the straightforward general solution. A 26-count tuple is efficient for lowercase English letters, and a sparse count key handles arbitrary code points without a fixed alphabet. State the input contract, preserve duplicate occurrences, prove both directions of the canonical-key equivalence, and distinguish expected hash-table complexity from unconditional worst-case behavior.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models