Q&A-1Explain backtracking as a search over a decision tree and how it changes a production decision.
Answer
Core answer
Backtracking is depth-first search over a tree of partial solutions. Each level of the tree fixes one decision; the search extends a partial candidate, recurses, then undoes the extension so one mutable state object serves every branch. The undo is the whole trick: without it, state from one branch leaks into its siblings and results become order-dependent.
The production decision it changes is whether a search-based feature ships at all, and with which engine. Backtracking is the right call when the decision tree is small after pruning and you need an exact answer. It is the wrong call when the tree is exponential and pruning cannot cut it, then you move to memoisation, a heuristic, or a solver.
Mechanism
The skeleton is three lines: choose, explore, unchoose.
def solve(state, level): # Python 3.12
if level == n:
return [state.copy()] # complete candidate
out = []
for choice in candidates(state, level):
state.append(choice) # choose
out += solve(state, level + 1) # explore
state.pop() # unchoose
return outWorst case is O(b^d) time for branching factor b and depth d, with O(d) stack. Pruning is what turns that bound into a budget: a constraint checked at each level removes whole subtrees, so the number you measure is nodes visited, not b^d.
Trace: 4-queens, one queen per row, reject any column that attacks an earlier queen:
| row | surviving partial placements | count |
|---|---|---|
| 0 | (0),(1),(2),(3) | 4 |
| 1 | (0,2),(0,3),(1,3),(2,0),(3,0),(3,1) | 6 |
| 2 | (0,3,1),(1,3,0),(2,0,3),(3,0,2) | 4 |
| 3 | (1,3,0,2),(2,0,3,1) | 2 |
16 nodes visited, 2 solutions. The unpruned tree is 4+16+64+256 = 340 nodes, so pruning cut it ~21×, and the cut grows with n.
Trade-offs
| approach | wins when | cost |
|---|---|---|
| backtracking + pruning | exact answer, small pruned tree, cheap constraint checks | exponential worst case; returns first solution found, not the best |
| memoised DP | the same partial state is reachable many ways | needs a hashable state; O(states) memory |
| greedy / local search | huge space, approximate answer acceptable | no exactness, can stall in local optima |
| SAT / CP-SAT solver | large space, need optimality or a proof | dependency, encoding cost, non-trivial latency |
Deciding criterion: if the same partial state is reachable by many paths, memoise; if the space is exponential and pruning cannot cut it, a solver's clause learning beats hand-rolled backtracking.
Failure modes
- Exponential blowup: no pruning or weak pruning → timeout. Detect by logging nodes visited per request; if it tracks b^d, pruning is not firing. Fix with forward checking or constraint propagation.
- Stack depth: recursion depth equals d, and Python's default limit is 1000 (
sys.getrecursionlimit()), so d near that raises RecursionError. Convert to an explicit stack. - State leak: a missed undo makes results order-dependent. The same input gives different answers on repeated runs. Detect by running the same input twice and diffing.
- No optimality: backtracking returns the first complete candidate, not the cheapest. If you need the minimum, search all or add branch-and-bound with a bound.
The production decision
Concretely: a dependency resolver that backtracks over version choices. Suppose a real lockfile gives b≈10 and d≈20 (hypothetical figures); b^d is 10^20, and no pruning survives that, so the decision is to move to a CP-SAT solver with conflict-driven clause learning, or to bound the search with a timeout and fall back to a heuristic. If the pruned tree stays in the thousands of nodes, keep the backtracking search: it is exact, dependency-free, and its cost is measurable. The number that decides it is p99 nodes visited on real lockfiles: instrument it before choosing.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.