~/problems
Problems
Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.
Recursion and backtracking
Choose, recurse, un-choose: subsets, permutations, N-queens, pruning.
Notes
Recognise it when: you're asked for all subsets, permutations or combinations, a placement puzzle (N-queens, sudoku), a word search, or n is small (<= ~15-20).
def backtrack(start, path):
out.append(path[:]) # record (subsets) or check completeness
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue # skip duplicates (sort first)
path.append(nums[i]) # choose
backtrack(i + 1, path) # explore (i, not i + 1, allows reuse)
path.pop() # un-choose
Gotchas
- Append a copy (
path[:]), not the list you keep mutating. - Prune early: check constraints before you recurse, not after.
- Permutations use a
usedarray. For combinations, passstart.
19 problems
Interview roadmap
Backtracking Recursion that tries, undoes and tries again.
- Basics: choose k of n (choose, explore, un-choose) basics py · c++ · java easy
- Seating plan without feuding neighbours py · c++ · java easy
- Subsets py · c++ · java easy
- Permutations py · c++ · java easy
- Combination Sum py · c++ · java medium
- N-Queens py · c++ · java medium
- Split apples into two fair groups py · c++ · java easy
- Pandigital Sum Citadel medium
- Currency Exchange CoinbaseOptiver medium
- Undo a run-length "say" encoding Pinterest py · c++ · java medium
- Combination Sum II py · c++ · java medium
- Subsets II py · c++ · java medium
- Word Search py · c++ · java medium
- Palindrome Partitioning py · c++ · java medium
- Letter Combinations of a Phone Number py · c++ · java medium
- Permutations II py · c++ · java medium
- Combinations py · c++ · java medium
- Word Break II py · c++ · java hard
- Partition to K Equal Sum Subsets py · c++ · java medium