← Arrays & Hashing
Problem
Given a list of strings, group the ones that are anagrams of each other into their own sublists.
30 MIN00:00unlocks in 30:00
Signal
Grouping items that share a "same under rearrangement" property means finding a canonical key each item maps to, then bucketing by that key in a hash map — anagram families all collapse to the same canonical form.
Approach
For each word, compute a canonical key — a fixed-length tuple of character counts works, and avoids sorting. Use the key as a hash map key and append the original word to that key's bucket. Return the buckets' values.
Skeleton
groups = defaultdict(list)
for word in words:
key = canonical(word) # 26-length count tuple, not sorted chars
groups[key].append(word)
return list(groups.values())
Solution
from collections import defaultdict
def group_anagrams(strs: list[str]) -> list[list[str]]:
groups: dict[tuple[int, ...], list[str]] = defaultdict(list)
for word in strs:
counts = [0] * 26
for ch in word:
counts[ord(ch) - ord('a')] += 1
groups[tuple(counts)].append(word)
return list(groups.values())
Complexity
O(n · k) time and space, where n is the number of words and k the max word length — building each count-key is O(k), versus O(k log k) if you sort each word instead.
Pitfalls
''.join(sorted(word))as the key is the natural first idea and works, but costs O(k log k) per word instead of O(k) — name both, lead with counting.- The 26-length tuple assumes lowercase English letters; for an unknown
alphabet or Unicode, fall back to a sorted-string or
Counter-based key. - The count key must be a tuple, not a list — lists aren't hashable and can't be a dict key.
locked30:00 left