Skip to content
Tech Interview Prep
Technical interview guide

Backtracking

Recursive brute-force search with early pruning: build a partial solution, and abandon it the moment it can't possibly work.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with generator and recursion behaviour cited from CPython 3.14.

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

2n2^n subsets of n elements, with every node a valid subset.

n!n! permutations, so n beyond about eleven is rejected at design time.

(nk)\binom{n}{k} k-combinations, generated with a start index.

(m+n−2m−1)\binom{m+n-2}{m-1} 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 1b−1\frac{1}{b-1} 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.
empty path choose 1 choose 2 choose 2 choose 3 leaf 1 2 3 leaf 1 3 2 choose 1 leaf 2 1 3

When to use and when not to

Use backtracking whenChoose something else when
The answer is a sequence of decisions and partial candidates can be rejected earlyOnly a count is needed: a closed form or an aggregating DP
Subproblems repeat over a compact stateThe state includes the whole path, so nothing repeats: prune instead
No polynomial formulation is known and the instance is modest or structuredA local rule is provably optimal: greedy
You must enumerate all valid configurationsThe input is untrusted and no node budget is in place
Permutations with n of about eleven or fewerPermutations with n of thirteen or more: rethink the formulation

Traps interviewers probe

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.