Try it first — give it 20 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get a list of words, strs. Group the words that are anagrams of each other, and return the groups in any order.
["eat", "tea", "tan", "ate", "nat", "bat"] → [["eat","tea","ate"], ["tan","nat"], ["bat"]]
Start with brute force
For each word, compare it against the first word of every existing group using the Valid Anagram check, and add it to the first group that matches. With n words of length k, that's up to n² comparisons of O(k) each — O(n² · k). Too slow for 10,000 words.
Building the intuition
The brute force keeps asking "does this word belong with that word?" Instead, ask "what label would every anagram of this word share?"
If we can compute a label (a key) that is identical for all anagrams and different for everything else, a hash map does the grouping for free: key → list of words.
Two good keys:
- Sorted letters.
"eat" → "aet","tea" → "aet","tan" → "ant". Costs O(k log k) per word. - Letter counts. A tuple of 26 counts, like
(1,0,0,0,1,…,1,…). Costs O(k) per word.
Sorting is simpler to write and explain, so it's what most people use in interviews. Mention counting as the optimisation.
The optimal approach
- Create a hash map
groupsfrom key → list of words. - For each word, compute
key = sorted letters of word. - Append the word to
groups[key](create the list if it's new). - Return all the lists in the map.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = defaultdict(list) # key -> words sharing that key
for word in strs:
key = "".join(sorted(word)) # "eat", "tea", "ate" -> "aet"
groups[key].append(word)
return list(groups.values())class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> groups; // key -> words sharing it
for (const string& word : strs) {
string key = word;
sort(key.begin(), key.end()); // "eat" -> "aet"
groups[key].push_back(word);
}
vector<vector<string>> result;
for (auto& [key, words] : groups) {
result.push_back(words);
}
return result;
}
};class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> groups = new HashMap<>(); // key -> words
for (String word : strs) {
char[] letters = word.toCharArray();
Arrays.sort(letters);
String key = new String(letters); // "eat" -> "aet"
groups.computeIfAbsent(key, k -> new ArrayList<>()).add(word);
}
return new ArrayList<>(groups.values());
}
}/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function (strs) {
const groups = new Map(); // key -> words sharing that key
for (const word of strs) {
const key = [...word].sort().join(""); // "eat" -> "aet"
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(word);
}
return [...groups.values()];
};Dry run
["eat", "tea", "tan", "ate", "nat", "bat"]
| word | key | groups after |
|---|---|---|
| eat | aet | aet: [eat] |
| tea | aet | aet: [eat, tea] |
| tan | ant | aet: [eat, tea], ant: [tan] |
| ate | aet | aet: [eat, tea, ate], ant: [tan] |
| nat | ant | …, ant: [tan, nat] |
| bat | abt | …, abt: [bat] |
Result: the three lists.
Complexity
With n words of maximum length k:
- Time: O(n · k log k) using sorted keys — we sort every word once. With counting keys it's O(n · k).
- Space: O(n · k) — the map stores every word once, plus its key.
Edge cases and traps
- Empty string
"". Its key is"", so all empty strings form one group. That's correct. - Single word. One group containing it.
- Using a list as a key. In Python, lists aren't hashable — convert to a string or a tuple. In Java, use a
String, not achar[](arrays compare by reference). - Counting keys without separators. If you build a string from counts like
"1" + "11", different counts can collide (1,11vs11,1). Put a separator between counts.
Say it in the interview
"Anagrams share the same sorted letters, so I use that as a key. I walk the words once, sort each word to get its key, and append the word to a hash map entry for that key. The map's values are the groups. That's O(n · k log k). If words are long, I can use a 26-count signature instead of sorting to get O(n · k)."
Follow-ups interviewers ask
- "Can you avoid sorting?" Use the 26-count signature as the key.
- "What if the input is a stream of words?" The same map works incrementally — each word is placed in O(k log k).
- "Return only groups with more than one word?" Filter the map's values at the end.
Practise the same idea
This is Day 12 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free