Backtracking Interview Problems: 8 Patterns That Get Offers
Backtracking interview guide: one template for N-Queens, Sudoku, Word Search, permutations.
20+ years shipping production code across the stack, with years spent interviewing engineers. Lessons pulled from things that broke in production.
- ✓Recursion and call-stack mental model
- ✓Python lists, sets, and copying semantics
- ✓Basic Big-O (factorial vs exponential)
- Backtracking = one template (choose → explore → unchoose) plus one constraint check per problem
- N-Queens prunes with column + two diagonal sets; never place an attacked queen
- Sudoku prunes with row/col/box sets and fewest-candidates-first (MRV) cell order
- Word Search prunes with per-path visited restore and rare-letter-first ordering
- Permutations/subsets/combinations differ only in choice rule and duplicate skipping
- In-place mutate-and-restore beats per-call copying by orders of magnitude past n = 15
Imagine exploring a maze with a ball of string: walk down a corridor (choose), and if it's a dead end, follow the string back (unchoose) and try the next corridor. You never redraw the whole map per attempt — you unwind your steps. Backtracking is that string: a single path you extend and retract while a rulebook (constraints) tells you which corridors are legal. N-Queens' rulebook bans shared diagonals, Sudoku's bans duplicate digits in a row, column, or box, and Word Search's bans reusing a cell. Same string, different rulebook.
| Chrome | Firefox | Safari | Edge |
|---|---|---|---|
| ✓ | ✓ | ✓ | ✓ |
Backtracking owns the hardest 15 minutes of coding interviews. N-Queens, Sudoku, Word Search, permutations — you've seen them on every 'top problems' list, and you still can't be sure you'd solve one live. Don't memorize four solutions. You'll drown. Learn one template and four constraint checks instead.
Here's the uncomfortable truth: every backtracking problem is the same three lines — choose, explore, unchoose — wrapped around a different validity test. Candidates who memorize boards fail the moment the interviewer tweaks the rules. Candidates who own the template adapt in seconds. Speed matters.
This guide gives you that template, then instantiates it four ways with runnable sketches: N-Queens with diagonal sets, Sudoku with box constraints, Word Search with visited restore, and the permutations/subsets/combination family. You'll also get pruning math that answers 'will this pass?' and an execution playbook for the whiteboard.
The One Template — Choose, Explore, Unchoose
All four problems compile to this skeleton. The base case records a snapshot. The loop enumerates candidates, prunes invalid ones BEFORE recursing, then does the three-beat: mutate, recurse, restore. Bugs live in exactly three places: missing snapshot (aliasing), missing restore (dirty state), prune-after-recurse (exponential blowup).
The problem-specific slots: candidates() is 'columns in this row' (Queens), 'digits 1-9' (Sudoku), '4 neighbors' (Word Search), 'unused elements from index i' (subsets). valid() is diagonal sets, box sets, visited+letter match, take/skip rules. Fill two slots, get a solution.
Practice drill: write the skeleton from memory 5 times, then fill Queens constraints without looking. That drill alone converts most 'I freeze' candidates into passers.
candidates() and valid() change per problem.N-Queens — Diagonal Sets Do the Pruning
Place one queen per row; the choice is the column. Constraints: no shared column, no shared ↙↗ diagonal (r−c equal), no shared ↖↘ diagonal (r+c equal). Three sets enforce all of it in O(1) per candidate.
Pruning power: row 0 tries n columns, but row 1 tries only n−2 or fewer — attacked columns and diagonals vanish before recursion. n=8 yields 92 solutions in milliseconds; the raw n^n fantasy (16M placements) never materializes because most branches die at depth 2.
Interview narration: 'one queen per row, three sets, snapshot the board at depth n.' That's a 60-second explanation that scores full marks on structure before you write a line.
Sudoku Solver — Box Sets Plus MRV Ordering
State: 9×9 board plus row/col/box digit sets. Choice: digit for the emptiest-constrained cell. Prune: digits already present in any of the three units never recurse. MRV ordering (minimum remaining values) picks the most constrained cell first, so contradictions surface at shallow depth.
Why MRV wins: a cell with 1 candidate forces the move; a cell with 7 candidates guesses. Row-major order guesses early and backtracks late — exponential waste. MRV on hard puzzles cuts solve time from seconds to milliseconds.
Box index arithmetic (r//3)*3 + c//3 maps 81 cells to 9 boxes. Get it wrong and valid boards reject — test box mapping on corners (0,0)→0, (0,8)→2, (8,0)→6, (8,8)→8 before running the solver.
Word Search — In-Place Visited With Restore
State: grid position plus matched-prefix length. Choice: 4 neighbors. Constraints: in-bounds, letter match, not visited (the '#' sentinel). Mark in place — no visited matrix copies — and restore on exit so sibling paths see a clean board.
Pruning that interviewers love: start DFS only from cells matching word[0]; rarer first letters prune harder. Early exits on length (word longer than cells) and letter-frequency counts (board lacks enough 'Z's) kill impossible cases in O(R×C) before any DFS.
Complexity honesty: worst case O(R×C×3^L) (4 first moves, ~3 thereafter excluding backtrack), but letter-match pruning collapses real boards. Say both numbers — the bound and why practice beats it.
Permutations, Subsets, Combination Sum — One Family
Permutations choose an ordering (used-array, any unused element); subsets choose membership (start-index, take-or-skip from i); Combination Sum adds a target with sorted early-stop (stop when remainder < 0) and same-index reuse for unlimited picks.
Duplicate handling is one rule: sort, then skip nums[i] when its twin nums[i−1] sits unused at the same level. That single line fixes Permutations II, Subsets II, and Combination Sum II identically.
Narrate the family mapping in interviews: 'permutations vary order, subsets vary membership, combinations add a sum target — same skeleton, different candidate rule.' Interviewers promote candidates who see families.
Pruning and Complexity — Answering Will This Pass
Raw bounds terrify: N-Queens O(n^n) placements, Sudoku O(9^81), Word Search O(4^L), permutations O(n!). Pruned reality: Queens places 92 solutions for n=8 in milliseconds, MRV Sudoku solves hard boards in milliseconds, Trie-guided Word Search II handles thousands of words on 12×12 boards.
The interview move is naming the effective branching: 'each queen kills a column and two diagonals, so depth-k branching is roughly n−2k'; 'MRV keeps Sudoku at 1–3 candidates per cell'; 'Trie guidance leaves ~1 live neighbor per Word Search step.' Numbers beat adjectives.
Time-box rule: if your search hasn't collapsed by depth 2, stop coding and add a constraint. No amount of micro-tuning saves unpruned exponential search — structure first, speed second.
Interview Execution Playbook — How to Present It Live
Minute 0–2: write the skeleton and label the two slots (candidates, valid). Interviewers score this instantly — it proves you've solved the class, not just an instance. Minutes 2–7: fill the slots with the constraint sets, narrating each ('columns, two diagonals').
Minutes 7–10: state complexity with pruning and run the smallest discriminating test (n=4 Queens → 2; 2×2 grid; [1,1,2] → 3 perms). Small tests catch diagonal arithmetic, aliasing, and skip-rule bugs in seconds.
Remaining time: invite follow-ups ('want duplicates handled? Trie-guided multi-word?'). Candidates who finish the core in 10 minutes and spend 20 on variants get hired; candidates who perfect one board for 40 minutes don't.
The Memorized N-Queens That Died on Word Search
- Interviewers mutate known problems deliberately — templates survive, memorized boards don't.
- Copying state per call is a TLE time bomb; in-place restore is non-negotiable past n = 15.
- Say the complexity WITH pruning before coding; it buys trust and guides cell ordering.
| File | Command / Code | Purpose |
|---|---|---|
| backtrack_template.py | def backtrack(path, choices): | The One Template |
| n_queens_sketch.py | def solve_n_queens(n): | N-Queens |
| sudoku_sketch.py | def solve_sudoku(board): | Sudoku Solver |
| word_search_sketch.py | def exist(board, word): | Word Search |
| perm_subsets_sketch.py | def permute_unique(nums): | Permutations, Subsets, Combination Sum |
Key takeaways
Common mistakes to avoid
4 patternsCopying the path or visited set on every recursive call
Appending the live path reference instead of a snapshot
Checking constraints after recursing instead of before, or forgetting to undo them
Quoting O(n!) / O(9^81) complexity with no pruning analysis
Interview Questions on This Topic
How do you handle duplicates in permutations?
Frequently Asked Questions
20+ years shipping production code across the stack, with years spent interviewing engineers. Lessons pulled from things that broke in production.
That's Coding Patterns. Mark it forged?
3 min read · try the examples if you haven't