Group Anagrams
Difficulty: Medium · Pattern: Hashing · LeetCode #49
Given a list of lowercase strings strs, group together the strings that are anagrams of each other. Return the groups in any order; the strings inside each group may also be in any order.
Example
text
strs = ["tea", "ate", "bat", "eat", "tab", "cat"]
→ [["tea","ate","eat"], ["bat","tab"], ["cat"]]Constraints: 1 ≤ strs.length ≤ 10⁴, 0 ≤ strs[i].length ≤ 100
Hints
- Two words are anagrams iff they have the same multiset of letters. What hashable value captures that?
- Sorting a word's letters gives the same string for all its anagrams.
- A tuple of 26 letter counts is another valid key, avoiding the sort.
Approach
Map each word to a canonical key shared by all its anagrams, then bucket words by key in a hash map.
- Key = sorted letters:
"tea" → "aet". Cost O(k log k) per word of length k. - Key = tuple of 26 counts: O(k) per word. Better for long words.
The values of the map are the groups.
Complexity
Time: O(n·k) with count keys (O(n·k log k) with sorted keys), for n words of max length k. Space: O(n·k).
Python solution
from collections import defaultdict
def groupAnagrams(strs):
groups = defaultdict(list)
for w in strs:
counts = [0] * 26
for ch in w:
counts[ord(ch) - 97] += 1
groups[tuple(counts)].append(w)
return list(groups.values())JavaScript solution
function groupAnagrams(strs) {
const groups = new Map();
for (const w of strs) {
const key = [...w].sort().join('');
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(w);
}
return [...groups.values()];
}