Group Anagrams
Group strings that are anagrams of each other. Return the groups in any order.
Answers use simple, clear English.
Audio N/AQuick interview answer
Use a hash map keyed by a sorted tuple of characters (or a 26-count signature). Append each string to its bucket. O(n * k log k) with sorting keys, or O(n * k) with counts.
Detailed answer
Use a hash map keyed by a sorted tuple of characters (or a 26-count signature). Append each string to its bucket. O(n * k log k) with sorting keys, or O(n * k) with counts. Unicode-heavy inputs need careful keying beyond 26 lowercase letters.
Full explanation
Unicode-heavy inputs need careful keying beyond 26 lowercase letters.
Real example & use case
Search backend grouping misspelled product titles that share the same letter multiset.
Pros & cons
Pros: clean grouping. Cons: sorted-key cost; count arrays assume alphabet size.
Code example
from collections import defaultdict
def group_anagrams(strs: list[str]) -> list[list[str]]:
buckets: dict[tuple[str, ...], list[str]] = defaultdict(list)
for s in strs:
key = tuple(sorted(s))
buckets[key].append(s)
return list(buckets.values())Practice code · python (view only · no execution)
from collections import defaultdict
def group_anagrams(strs: list[str]) -> list[list[str]]:
buckets: dict[tuple[str, ...], list[str]] = defaultdict(list)
for s in strs:
key = tuple(sorted(s))
buckets[key].append(s)
return list(buckets.values())