Backtracking

On this page 7

Backtracking is an algorithm design technique that builds a solution incrementally, one decision at a time, and undoes the most recent decision as soon as it becomes clear that the current partial solution cannot be completed. In programming and the study of algorithms, it is the standard systematic way to search a space of combinations, permutations or assignments without enumerating every candidate blindly.

The technique is a refinement of exhaustive search. Its power comes from pruning: by testing constraints early, backtracking discards whole branches of the search space at once, which often turns an impractical brute-force search into one that finishes in seconds. It underpins solvers for puzzles, scheduling, parsing and constraint satisfaction.

How backtracking explores the state space tree

Backtracking works by performing a depth-first traversal of an implicit state space tree, in which each node represents a partial solution and each edge represents one choice. The root is the empty solution, internal nodes are partial assignments, and leaves are either complete solutions or dead ends. The tree is never stored in memory; it exists only as the sequence of recursive calls.

At every node the algorithm repeats the same cycle. It chooses an option, checks feasibility against the constraints, recurses if the partial solution is still promising, and unchooses the option on return so that the next alternative starts from a clean state. This choose-explore-unchoose pattern is the recognizable signature of the technique.

The following table summarizes the components that every backtracking implementation must define.

ComponentRoleExample with eight queens
Candidate choicesOptions available at the current levelColumns where the next queen may go
Feasibility testRejects partial solutions that violate a constraintNo two queens share a column or diagonal
Goal testRecognizes a complete valid solutionAll N rows contain a queen
State update and undoApplies a choice, then reverts it on returnMark and unmark attacked columns and diagonals
Ordering heuristicDecides which choice to try firstTry the most constrained row first
Core components of a backtracking algorithm

Because the traversal is depth-first, memory use is proportional to the depth of the tree, not its size. A search over billions of nodes may need only a recursion stack of a few dozen frames, which is a decisive practical advantage over breadth-first strategies.

Pruning and its effect on complexity

Pruning is the act of abandoning a branch before reaching its leaves because a constraint is already violated or because the branch cannot improve on the best known solution. Without pruning, backtracking degenerates into plain enumeration with a time complexity equal to the number of leaves, such as O(n!) for permutations or O(2^n) for subsets.

The worst-case time complexity usually stays exponential even with good pruning, because many backtracking problems are NP-complete. What changes is the practical running time: effective pruning shrinks the number of visited nodes by many orders of magnitude on typical inputs. The table below lists common problems with their raw search space and the pruning that makes them tractable.

ProblemUnpruned search spaceMain pruning rule
N-queensN^N placementsReject a queen attacked by an earlier one
Sudoku9^k for k empty cellsReject a digit already present in row, column or box
Subset sum2^n subsetsStop when the running sum exceeds the target
Graph coloringk^V assignmentsReject a color used by an adjacent vertex
Permutation generationn! orderingsSkip elements already used or duplicate values
Typical backtracking problems and their pruning rules

Two further refinements strengthen pruning. Constraint propagation, also called forward checking, removes values from the domains of unassigned variables as soon as a choice is made, so dead ends are detected one level earlier. Branch and bound extends backtracking to optimization problems by keeping the best cost found so far and cutting any branch whose lower bound already exceeds that cost.

Backtracking is best understood as depth-first search with constraint checks and state restoration applied to a decision tree rather than to an explicit graph. It shares ideas with several neighboring strategies but differs in what it stores and how it decides.

StrategyExploresKey difference from backtracking
Brute forceEvery complete candidateNo early rejection of partial solutions
Depth-first searchNodes of an explicit graphVisits reachable nodes; backtracking adds constraint-driven pruning
Dynamic programmingOverlapping subproblemsReuses stored results instead of re-exploring branches
Greedy algorithmA single path of locally best choicesNever revisits a decision, so it may miss the optimum
Branch and boundA tree with cost boundsOptimization variant that prunes by cost, not only feasibility
How backtracking differs from neighboring strategies

The boundary with dynamic programming is important in practice. When different branches reach identical subproblems, adding memoization to a backtracking routine can collapse exponential repetition into polynomial work. When subproblems rarely repeat, as in most constraint satisfaction puzzles, memoization adds memory cost without benefit.

Implementing backtracking correctly

A correct implementation needs a clear representation of state, a cheap feasibility check and a reliable undo step. Most code uses recursion, where the call stack naturally records the path, but an explicit stack works equally well and avoids recursion depth limits in languages such as Python.

  • Keep the state in mutable structures that are modified and restored, such as boolean arrays for used columns, rather than copying the whole state at each level.
  • Make the feasibility test incremental, checking only what the newest choice could have broken, so each node costs constant or near-constant time.
  • Order choices with heuristics such as minimum remaining values, which picks the variable with the fewest legal options and exposes failures early.
  • Return immediately after the first solution when only one is needed; continue the search when all solutions or the best one must be found.

The next table matches typical requirements with the appropriate backtracking variant.

RequirementRecommended approachReason
Any one valid solutionStop at the first goal stateAvoids exploring the rest of the tree
All valid solutionsRecord each goal and continueEvery leaf must be examined or pruned
Optimal solutionBranch and bound with a cost boundCuts branches that cannot beat the incumbent
Many repeated subproblemsBacktracking with memoizationPrevents recomputing identical states
Large constraint networksForward checking and propagationDetects dead ends before descending
Choosing a backtracking variant

Limitations and common mistakes

The main limitation is that worst-case running time remains exponential. Adversarial or unconstrained inputs leave little to prune, and the search may run for an impractically long time. For very large instances, practitioners switch to SAT solvers, integer programming or heuristic methods such as local search, which trade guarantees for speed.

Most bugs come from incomplete undo operations. If a choice modifies several structures and only some are restored, later branches inherit a corrupted state and produce wrong or missing solutions. A second frequent error is checking constraints only at the leaves, which silently removes all the benefit of pruning while still producing correct output, so the defect appears only as poor performance.

Stripped to the essentials

Backtracking is a way of solving a problem by trying options one at a time and stepping back when a choice leads nowhere. Think of walking through a maze. At each fork you pick a path. If you hit a wall, you return to the last fork and try another way.

The clever part is simple. You give up on a path as soon as it is clearly wrong. You do not walk all the way to its end. That habit lets a computer solve huge puzzles without checking every possible answer.

Where it is applied

A university registrar needs to schedule 120 final exams into 15 time slots across 20 rooms, with constraints that no student sits two exams at once, room capacities are respected and certain courses avoid evening slots. The development team models each exam as a variable whose domain is the set of slot and room pairs.

The solver uses backtracking with forward checking and the minimum remaining values heuristic. It assigns the most constrained exams first, such as large first-year courses shared by many programs, and removes conflicting slots from the domains of related exams after each assignment. When an exam is left with no legal slot, the solver backs up and changes an earlier decision.

A naive enumeration would face an astronomically large number of combinations. With pruning, the solver produces a conflict-free timetable in under a minute on an ordinary laptop, and the team reruns it whenever enrollment data changes.