Overview
Curated: · Written: · Reviewed:
Backtracking
In one line
A depth-first search over partial solutions that undoes each choice on return and abandons a partial candidate as soon as it cannot extend to a solution. Reach for it when the answer is a sequence of decisions, constraints can reject partial candidates early, and no polynomial formulation exists.
Key definitions
- Choose-explore-unchoose: make a decision, recurse, then undo it, in that fixed order.
- Prune: reject a partial candidate and its whole subtree because it provably cannot reach a solution.
- Constraint propagation: deduce forced values after a decision, recording each change on a trail so it can be rolled back.
- Incumbent: the best complete solution verified so far, used by branch and bound.
- Optimistic bound: an estimate of the best result a subtree can reach that never understates it.
- Symmetry breaking: a canonical-form rule that removes equivalent branches without losing solutions.
Formulas and complexity
subsets of n elements, with every node a valid subset.
permutations, so n beyond about eleven is rejected at design time.
k-combinations, generated with a start index.
monotone paths across an m by n grid, which is a count, not an enumeration.
The worst case stays exponential whatever the pruning. Pruning changes typical time, not the bound. For iterative deepening with branching factor b, re-expanding the shallower levels costs about of the last level.
How it works
Each level fixes one decision. The state is one mutable structure shared by every branch, and the undo is what keeps siblings independent.
- Validate at the decision, not at the leaf. Validating 8-queens on placement explores 2,057 nodes; validating only at the leaves generates the full tree.
- Put the undo on the line directly after the recursive call. A skipped undo leaks state into sibling branches.
- Record at every node for subsets, and only at complete solutions for permutations and fixed-length results.
- Copy once, when recording. Appending the live list stores aliases that later mutations overwrite.
- With duplicates, sort first and skip a value equal to the previous one at the same level.
When to use and when not to
| Use backtracking when | Choose something else when |
|---|---|
| The answer is a sequence of decisions and partial candidates can be rejected early | Only a count is needed: a closed form or an aggregating DP |
| Subproblems repeat over a compact state | The state includes the whole path, so nothing repeats: prune instead |
| No polynomial formulation is known and the instance is modest or structured | A local rule is provably optimal: greedy |
| You must enumerate all valid configurations | The input is untrusted and no node budget is in place |
| Permutations with n of about eleven or fewer | Permutations with n of thirteen or more: rethink the formulation |
Traps interviewers probe
- Validating only at the leaves. The search generates the whole tree and discards most of it. Fix: check each constraint at the decision that breaks it.
- Missing or misplaced undo. Results change with the order options are tried. Fix: write the undo directly after the recursive call and assert the state is unchanged afterwards in tests.
- A global visited set in grid search. It blocks cells that another path could use. Fix: unmark on return, so the marker is per path.
- Memoising on the whole path. No two states match, so the cache never hits and memory grows. Fix: memoise only a compact state such as (index, remaining), or prune.
- A pessimistic bound in branch and bound. The search is faster and silently wrong. Fix: prove the bound never understates the best value, and compare against exhaustive search on small instances.
Interview tips
Open with the decision tree: 'Each level makes one decision, I mutate shared state, recurse, and undo.' Then name the prune, since that is what makes it usable.
Follow-ups to expect:
- Where does the prune come from, and which constraint does it enforce?
- What is the worst case, and what does pruning change about it?
- How do you handle duplicates in the input?
- What happens at depth 5,000? Recursion depth equals the number of decisions, so switch to an explicit stack.
- How do you bound the work on untrusted input? Count expanded nodes against a budget, because a request timeout does not stop the worker.
- How do you know the result is complete? Compare against a brute-force generator on small inputs.
30-second answer outline: 'Backtracking is a depth-first search over partial solutions. Each level makes one decision, recurses, and undoes it, so one shared state serves every branch. I prune at the decision as soon as a constraint fails, which removes whole subtrees. The worst case is still exponential, so I measure the explored node count on realistic instances, add a node budget if the input is untrusted, and check completeness against brute force on small cases.'
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.