Jump to section
Group Anagrams asks you to split a list of words into groups, where each group holds words that are anagrams of each other. The standard solution gives every word a key that all its anagrams share, such as its letters in sorted order, and collects words by key in a hash map. With n words of length up to k, it runs in O(n · k log k) time.
The Group Anagrams Problem
You are given a list of words. Group together the words that are anagrams of each other, meaning they use the same letters the same number of times. Return the groups in any order, and the words within a group in any order.
Example 1
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
Output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
Why: "eat", "tea" and "ate" all use a, e and t once each. "bat" has no anagram in the list, so it forms a group of one.
Example 2
Input: [""]
Output: [[""]]
Why: an empty word is still a word, and it gets its own group.
Assumptions to confirm
- Lowercase letters only? (It decides whether a 26-count key is an option.)
- Does the order of groups or of words inside a group matter? (Usually not.)
- Can the same word appear twice? (Then it appears twice in its group.)
Start With the Brute Force
The direct approach compares every word with every other word using an anagram check, joining words into a group whenever they match. With n words that is O(n²) comparisons, each costing O(k) for words of length k.
Mention it, then ask the question that unlocks the problem: what do all anagrams of a word have in common that I could compute once per word? If you can turn each word into a key that only its anagrams share, a hash map does the grouping in one pass, and you never compare two words directly.
Ready to put this into practice?
Practice this with MockIF →Still applying for jobs? Let Auto Apply do it
Group Anagrams Solution in Python and TypeScript
Both versions use the sorted-letters key, which is the answer most interviewers expect first.
Python
from collections import defaultdict
def group_anagrams(words: list[str]) -> list[list[str]]:
groups: dict[str, list[str]] = defaultdict(list)
for word in words:
key = "".join(sorted(word)) # anagrams share the same sorted letters
groups[key].append(word)
return list(groups.values())
TypeScript
function groupAnagrams(words: string[]): string[][] {
const groups = new Map<string, string[]>();
for (const word of words) {
const key = [...word].sort().join(""); // anagrams share the same sorted letters
const group = groups.get(key);
if (group) group.push(word);
else groups.set(key, [word]);
}
return [...groups.values()];
}
If the interviewer asks for something faster, switch the key to letter counts: build an array of 26 zeros, count each letter, and use the array (as a tuple in Python, or joined into a string in TypeScript) as the key. That removes the sort from the inner step.
Ready to put this into practice?
Practice this with MockIF →Still applying for jobs? Let Auto Apply do it
Time and Space Complexity
| Approach | Time | Space | When to use it |
|---|---|---|---|
| Compare every pair | O(n² · k) | O(n · k) | Only as your first spoken answer |
| Sorted-letters key | O(n · k log k) | O(n · k) | The usual interview answer |
| Letter-count key | O(n · k) | O(n · k) | Long words over a fixed alphabet |
How to Talk Through Group Anagrams in an Interview
A strong spoken answer follows the same five beats every time:
- Clarify: "Lowercase letters only? Does the order of the groups matter?"
- Brute force: "I could compare every pair of words with an anagram check, but that is quadratic in the number of words."
- Optimise: "Anagrams have the same letters, so if I sort each word's letters I get a key they all share. Grouping by that key in a hash map is one pass."
- Code: explain the key, and what happens the first time you see a new key.
- Test: walk through the six-word example, then an empty string and a word with no anagram. State O(n · k log k) time.
Naming the two sizes separately, n for the number of words and k for word length, makes your complexity answer much clearer.
Ready to put this into practice?
Practice this with MockIF →Still applying for jobs? Let Auto Apply do it
Edge Cases and Common Follow-Ups
Empty strings
The sorted key of "" is "", so empty words group together correctly.
Single words
A word with no anagram is a valid group of one; do not drop it.
Faster keys
Use a 26-count key to avoid sorting when words are long.
Unicode
The sorted key works for any characters. A 26-count key only works for lowercase English letters.
Return only the largest group
Track the size of each group as you go and keep the biggest; the grouping step does not change.
Practise Group Anagrams in a Mock Coding Round
Group Anagrams is a common follow-up to Valid Anagram, which makes it a good test of whether you can reuse an idea under pressure. The skill is spotting the shared key quickly and saying why it works, out loud, before you write the code.
MockIF runs mock coding interviews with a voice AI interviewer in a real in-browser editor, in Python and TypeScript. It runs your code against tests, asks you to explain your approach, adds follow-up questions the way a real interviewer would, and then scores your answer and gives specific feedback. Each session costs 2 credits. It is free to start with 5 credits, then monthly or 3-monthly plans, or one-off credit packs (see pricing).
Frequently Asked Questions
How do you group anagrams together?
What is the time complexity of Group Anagrams?
Why use sorted letters as the key?
Is Group Anagrams a medium problem?
Stop Preparing in Your Head. Start Practicing Out Loud.
Drop your resume, add a job description, and get a mock interview like the real thing.
Start Free Mock Interview →Still applying for jobs? Let Auto Apply do it for you.