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.
# ─── GROUP ANAGRAMS (LeetCode 49) ───
# Pattern: Sorted string as key
# Time: O(n · k log k) Space: O(n)
#
# 1. Define: groupAnagrams(strs)
#
# 2. Init groups dict:
# groups = {} ← key → list of anagrams
#
# 3. Loop over each string:
# for s in strs:
#
# 4. Build canonical key (sorted tuple):
# key = tuple(sorted(s)) ← anagrams share same key
#
# 5. Init list if first of this key:
# if key not in groups:
# groups[key] = []
#
# 6. Append current string:
# groups[key].append(s)
#
# 7. Return all groups: return list(groups.values())
#
# Vars: groups (dict), key, s
▼ your implementation ▼
Verify your solution: