Group Anagrams
LeetCode 49 • Medium • Arrays & Hashing
Group strings that are anagrams. Key = sorted(s). Iterative: hash map in one pass. Recursive: group rest, merge first.
TimeO(n·k log k)n strings, sort each k chars
SpaceO(n)groups dict
i: —
key: —
Ready
Press Play. For each string: key = sorted(s), append to groups[key]. Anagrams share the same key.
TimeO(n·k log k)same, recursive merge
SpaceO(n)output + call stack
Recursive: group(strs) = if empty return []; else key = sorted(first), rest = group(rest), find matching group or append new.
Practice until you don't need to look. Use the guide comments below as scaffolding. The green highlights are the nuances to burn into memory.
PATTERN ▸ Sorted string as key O(n·k log k) · O(n)
① INIT
groups = {}
② LOOP OVER STRINGS
for s in strs:
③ BUILD KEY & APPEND
key = tuple(sorted(s))
if key not in groups: groups[key] = []
groups[key].append(s)
④ RETURN
return list(groups.values())
▼ your implementation ▼
Verify your solution: