Backtracking
exponential
Choose → recurse → un-choose. Prune as early as the constraints allow to cut the search tree.
0/14 solved
Recognise it
The signal
"Find all valid ...", "is there a way to ...": N-Queens, Sudoku, word search, string partitions, valid parentheses, with early-checkable rules.
1Brute force
Generate every full candidate, then test validity.
2The observation
Building invalid completions: early constraint checks cut whole subtrees.
3Why it works
The current partial assignment always satisfies every constraint checked so far; choose, recurse, un-choose keeps one path in memory.
Reach for it when
- +Build a configuration incrementally with constraints you can check early — board placement, partitions, valid strings.
- +'Find all valid …', 'is there a way to …', or 'solve this puzzle' (Sudoku, N-Queens, word search).
- +The search space is exponential but pruning cuts most of it.
Not when
- ×Only a count or optimum is needed and subproblems overlapuse Memoise it: DP
- ×The used-set state repeats across pathsuse Memoise on the mask: bitmask DP
- ×A provable greedy or formula existsuse Greedy; don't explore a tree you don't need
- ×Huge state space, weak pruning, and you need one answer fastuse BFS or heuristics
Intuition
Backtracking is subsets/permutations with a conscience: you build a candidate step by step, but the moment it can't possibly lead to a valid answer, you abandon that branch and rewind. It's how you solve a maze — walk forward, hit a wall, back up to the last fork, try another door.
Read the full intuition
It's the same "choose → recurse → un-choose" loop as enumeration, plus a third ingredient: a validity / pruning check before (or right after) you make a move. Good pruning is the whole game — N-Queens has 64-choose-8 raw placements, but checking "is this square attacked?" before placing chops the tree by orders of magnitude.
The reusable frame:
- Base case — path is a complete solution → record it.
- For each candidate move:
- if it's invalid, skip (prune).
- else place it, recurse, then remove it (backtrack).
Worked tiny example — Generate Parentheses, n=2. State = (open used, close used). You may add '(' while open<n, and ')' only while close<open (else it's unbalanced — pruned). That single close<open rule prevents every invalid string from ever being built.
Key idea
The skill to drill: spotting the earliest point you can prove a branch is dead. The earlier you prune, the faster everything runs.
Why it costs what it costs
Time exponential (problem-specific). worst case explores the whole decision tree; pruning cuts it dramatically but the bound stays exponential (e.g. roughly O(n!) for N-Queens).
Space O(depth). recursion stack plus the partial solution, both bounded by the solution length.
Practice
- Generate ParenthesesFoundationFoundationAmazon, MetaMedium
- Combination Sum IIApply it · Each element once with duplicates in input.Apply itAmazon, UberMedium
- Palindrome PartitioningOne change · Choose cut positions.One changeAmazon, UberMedium
- Restore IP AddressesOne change · Segment rules (0-255, no leading zeros).One changeMicrosoft, AdobeMedium
- Word SearchTwists · State is a grid path; must undo visited marks.TwistsMeta, AmazonMedium
- N-QueensBranches · Global constraints (columns, diagonals).BranchesAmazon, GoogleHard
- Word Search IICombine · Many words at once.CombineAmazon, GoogleHard
- Sudoku SolverMastery checkMastery checkGoogle, UberHard
- Chessboard and QueensCSESMedium
- Grid Path DescriptionCSESHard
- Filling TrominosCSESHard
- Good Permutations with Alternating ParityAtlassianOAEasy
- Word Break IIHard
- Matchsticks to SquareMedium
Pitfalls
Classic bugs
- !Weak or late pruning makes the tree explode: check validity before placing, at the earliest provable dead end.
- !Forgot to undo a change (unmark cell, pop choice): sibling branches see corrupted state.
- !Grid search: mark visited before recursing and restore after. Miss either and you loop or block paths.
- !Saved the live mutable path at the base case: append a copy. But copy only at leaves, not at every node.
- !N-Queens diagonals:
r-c(offset it, can be negative) andr+care the two diagonals; mixing them up is classic.
Looks like it, isn't
- Word Ladder needs Graph BFS / DFS
Why
Shortest transformation sequence is BFS on an implicit graph. - Word Break needs 1D / Fibonacci-style
Why
Backtracking repeats suffixes; dp over prefix positions. source ↗ - Palindrome Partitioning II needs Palindromic Substrings
Why
Only the minimum cut is needed: palindrome table + 1D cut DP. - Tallest Billboard needs 0/1 Knapsack
Why
3n assignments collapse into dp[difference] = best shorter-side height (the editorial also shows meet-in-the-middle). source ↗
Go deepervariants and techniques · 2 combinations · interviewer follow-ups · resources
Variants and techniques
- Divide and Conquer (merge-sort counting)Split the array in half, solve each half, then count/merge cross pairs in linear time while merging sorted halves.
- Constraint placementPlace items honoring constraints, track conflicts in sets/arrays. N-Queens, Sudoku Solver.
- Grid path searchDFS 4-directionally, mark visited, restore on exit. Word Search.
- PartitioningCut the input into pieces, recurse on the remainder, validate each piece. Palindrome Partitioning.
- Balanced constructionBuild a string/sequence honoring a running invariant (e.g. close<open). Generate Parentheses.
Combinations
Trie (Prefix Tree)+Backtracking
find all dictionary words in a grid
- Trie (Prefix Tree):
- prefix pruning for all words at once
- Backtracking:
- grid path enumeration with undo
Backtracking+Bit Tricks & Bitmasking
N-Queens, Sudoku, placement puzzles
- Backtracking:
- the search
- Bit Tricks & Bitmasking:
- O(1) constraint sets as bitmasks
Follow-ups interviewers ask
- 01Just the count of solutions, not all of them? → often a DP exists (overlapping subproblems) — far faster than enumerating.
- 02How do you prune earlier? → tighten the validity check (constraint propagation, sorted input + skip duplicates).
- 03Memory for huge output? → yield/stream solutions instead of materialising the whole list.
- 04Can it be parallelised? → independent subtrees from the first choice can run concurrently.
State table
| depth | choice | path | valid? | action |
|---|---|---|---|---|
| 0 | place '(' | ( |
open<2 ✓ | recurse |
| 1 | place '(' | (( |
open=2 ✓ | recurse |
| 2 | place ')' | (() |
close<open ✓ | recurse |
| 3 | place ')' | (()) |
len=4 ✓ | record, backtrack |