Group Anagrams solution explained
Group Anagrams is solved by giving every word a signature that all of its anagrams share, then using that signature as a dictionary key: words with the same key land in the same bucket. Sorting each word's letters gives a simple signature in O(n · k log k) total time, and a 26-count tuple gives O(n · k), where n is the number of words and k their length.
By Evin JohnPublished 6 min read
What the question asks
You are handed a list of lowercase words. Return them arranged in groups so that two words share a group exactly when one is an anagram of the other. The order of the groups, and the order of words inside each group, normally does not matter. Duplicate words go in the same group, and an empty string is a legal word that forms its own group with any other empty strings.
| Group | Members | Shared signature (sorted letters) |
|---|---|---|
| 1 | least, slate, stale, steal | aelst |
| 2 | night, thing | ghint |
| 3 | dusty, study | dstuy |
| 4 | ox | ox |
Clarify three things early: whether the input can contain capitals or non-letters, whether the output order is checked, and roughly how many words and how long they are. The last answer tells you which signature to prefer, because sorting cost grows with word length while counting cost does not grow faster than the length itself.
Why it shows up in interviews
The problem tests one transferable instinct: when items must be grouped by an equivalence, find a value that is identical for equivalent items and different otherwise, then hash on it. The same move groups files by content hash, log lines by template and shapes by normalized coordinates. Interviewers like it because it has a clear naive answer, a clear improvement and a subtle bug in the counting version that careful candidates catch.
Naive version: compare against each existing group
Keep a list of groups. For each word, test it against the first member of every group with an anagram check and append it to the first match, or start a new group. With n words and g groups that is up to n times g checks, each costing O(k) with counts, so the worst case is O(n² · k) when no two words match. It is correct, and saying it first makes the improvement obvious: the comparison work disappears if equal words can find each other directly.
Hashing on a signature
Signature 1: the sorted letters
Sort each word's characters and join them into a string. Every anagram of stale sorts to aelst, and no word with different letter counts can sort to the same string. Use that string as a key in a dictionary of lists and append the original word.
from collections import defaultdict
def bucket_by_sorted(words):
buckets = defaultdict(list)
for w in words:
buckets["".join(sorted(w))].append(w)
return list(buckets.values())Signature 2: the letter counts
Count how many times each of the 26 letters appears and use the counts as the key. In Python a tuple of 26 integers is hashable, so it works directly. In JavaScript you have to turn the counts into a string, and this is where the subtle bug lives: joining counts with no separator makes a count of 1 followed by 11 look like 11 followed by 1. Put a delimiter between counts and the ambiguity goes away.
def bucket_by_counts(words):
buckets = {}
for w in words:
tally = [0] * 26
for ch in w:
tally[ord(ch) - 97] += 1
buckets.setdefault(tuple(tally), []).append(w)
return list(buckets.values())function bucketByCounts(words) {
const buckets = new Map();
for (const w of words) {
const tally = new Array(26).fill(0);
for (let i = 0; i < w.length; i++) tally[w.charCodeAt(i) - 97] += 1;
const key = tally.join("#");
if (!buckets.has(key)) buckets.set(key, []);
buckets.get(key).push(w);
}
return [...buckets.values()];
}Both keys are correct. In an interview, writing the sorted version first and then mentioning the count version as the asymptotically better choice for long words is a strong sequence. For short words, sorting is often just as fast in practice, because building a 26-slot key has its own fixed cost per word.
Complexity side by side
| Approach | Time | Extra space |
|---|---|---|
| Compare with each group | O(n² · k) worst case | O(n · k) for the output |
| Sorted-letters key | O(n · k log k) | O(n · k) for keys and groups |
| 26-count key | O(n · k), plus O(26) per word to build the key | O(n · k) for groups, O(26) per key |
Inputs that break careless code
- An empty list: return an empty list, not a list with one empty group.
- Empty strings: they all share the empty key and belong together.
- Repeated words such as
oxtwice: both copies go in the same group. - A word with ten or more of one letter, to catch the missing delimiter in a string key.
- Capital letters or digits when your key assumes a to z: ask first, or use a dictionary of counts.
- Every word unique: n groups of one, which is also the worst case for the naive approach.
Common slips
- Using a Python list as a dictionary key. Lists are not hashable; convert to a tuple or a string.
- Using a JavaScript array as a
Mapkey. Two arrays with equal contents are different keys, so every word ends up alone. - Using a set of letters as the key, which merges
aabandabb. - Concatenating counts without a separator.
- Calling the sorted version O(n log n). The sort is per word, so the log factor belongs to k.
A spoken walkthrough
Fictional example
- Candidate
- The slow way is to compare each word with a representative of every group so far, which is quadratic in the number of words.
- Candidate
- Instead I want a key that is the same for all anagrams. Sorting the letters gives one: stale, steal and least all become a-e-l-s-t. I map that key to a list and append each word as I go.
- Candidate
- That is n times k log k. If words are long I can switch to a key of 26 counts, which makes it n times k. In JavaScript I would join the counts with a separator so that one-then-eleven and eleven-then-one stay different.
Where to go next
If the counting step felt new, Valid Anagram is the single-pair version and the right warm-up. Longest Consecutive Sequence uses a set as its key structure in a different way, and Top K Frequent Elements is another problem where hashing does the heavy lifting before a second step picks the answer. See the full list on the coding problems hub.
Practice support from Natively
Natively runs on Mac and Windows. In a practice session you can capture this kind of prompt with a screenshot and ask it for a hint on choosing a key, then compare its suggestion with what you wrote. It keeps a transcript of the mock so you can check later whether you explained the delimiter issue or skipped over it. More detail is on the AI assistant for coding interviews page.
Questions people ask
What is the best way to solve Group Anagrams?
Build a key that every anagram of a word shares, such as its sorted letters or its 26 letter counts, and append each word to a dictionary list under that key. One pass over the words fills every group.
Is a sorted-letter key or a count key faster?
The count key is O(k) per word against O(k log k) for sorting, so it wins on long words. For short words the sorted key is usually just as quick and easier to read, so either is a fine answer.
Why can't I use a list as a dictionary key in Python?
Lists are mutable, so they are not hashable. Convert the count list to a tuple, or join the sorted letters into a string, before using it as a key.
What is the time complexity of Group Anagrams?
With n words of length up to k, the sorted-key version is O(n · k log k) and the count-key version is O(n · k), each with O(n · k) space for the groups.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
