~/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.

Backtracking

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 used array. For combinations, pass start.

19 problems

Interview roadmap

Backtracking Recursion that tries, undoes and tries again.

esc