Group Anagrams
The problem
Section titled “The problem”You get a list of lowercase words. Group together the words that are anagrams of each other (same letters, any order). Return the groups in any order.
["eat", "tea", "tan", "ate", "nat", "bat"] -> [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]Key insight
Section titled “Key insight”Brute force compares every pair of words and checks if they are anagrams, which is O(n²) comparisons. The waste is that you compare words that were never going to match.
Give every word a canonical key that is identical for all anagrams and different
otherwise. Then one hash map from key to list of words does all the grouping in a single
pass. Two good keys: the word’s sorted letters ("eat" becomes "aet"), or a count of
each letter. The count key avoids sorting each word, so it is O(k) per word instead of
O(k log k). Mention both; code the count version.
Show solutionHide solution
from collections import defaultdict
def group_anagrams(strs: list[str]) -> list[list[str]]: groups = defaultdict(list) for word in strs: counts = [0] * 26 # letter frequencies are the same for all anagrams for ch in word: counts[ord(ch) - ord("a")] += 1 groups[tuple(counts)].append(word) return list(groups.values())export function groupAnagrams(strs: string[]): string[][] { const groups = new Map<string, string[]>(); for (const word of strs) { const counts = new Array<number>(26).fill(0); // same for all anagrams for (const ch of word) counts[ch.charCodeAt(0) - 97]++; const key = counts.join(','); if (!groups.has(key)) groups.set(key, []); groups.get(key)!.push(word); } return [...groups.values()];}import java.util.*;
class Solution { public List<List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> groups = new HashMap<>(); for (String word : strs) { int[] counts = new int[26]; // same for all anagrams for (char ch : word.toCharArray()) counts[ch - 'a']++; String key = Arrays.toString(counts); groups.computeIfAbsent(key, k -> new ArrayList<>()).add(word); } return new ArrayList<>(groups.values()); }}Complexity
Section titled “Complexity”Let n be the number of words and k the length of the longest word.
- Time: O(n·k) — each word is scanned once to build its 26-slot count, and the key is a fixed size of 26.
- Space: O(n·k) — the map stores every word once, plus a fixed-size key per group.
Watch out for
Section titled “Watch out for”- Lists can’t be dictionary keys in Python. Convert the count list to a
tuple. In TypeScript and Java, join or stringify the counts instead. - Delimit the counts in a string key. Joining
[1, 11]as"111"collides with[11, 1]. Use a separator, asArrays.toStringandjoin(',')do. - The empty string is valid input and forms its own group.
Variations
Section titled “Variations”Valid Anagram (LeetCode 242)
Section titled “Valid Anagram (LeetCode 242)”Are two strings anagrams of each other? The trick: compare letter counts. One 26-slot array, add for the first string, subtract for the second, check all zeros. If characters can be Unicode, use a hash map instead of a fixed array.
Find All Anagrams in a String (LeetCode 438)
Section titled “Find All Anagrams in a String (LeetCode 438)”Find every start index in s where a substring is an anagram of p. The trick:
slide a window of length len(p) over s, updating the letter counts by adding the
new character and removing the old one. Compare counts to p’s counts at each step.
Top K Frequent Words (LeetCode 692)
Section titled “Top K Frequent Words (LeetCode 692)”Return the k most frequent words, ties broken alphabetically. The trick: count
with a hash map, then sort or use a heap with the key (-count, word).