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.
| Component | Role | Example with eight queens |
|---|---|---|
| Candidate choices | Options available at the current level | Columns where the next queen may go |
| Feasibility test | Rejects partial solutions that violate a constraint | No two queens share a column or diagonal |
| Goal test | Recognizes a complete valid solution | All N rows contain a queen |
| State update and undo | Applies a choice, then reverts it on return | Mark and unmark attacked columns and diagonals |
| Ordering heuristic | Decides which choice to try first | Try the most constrained row first |
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.
| Problem | Unpruned search space | Main pruning rule |
|---|---|---|
| N-queens | N^N placements | Reject a queen attacked by an earlier one |
| Sudoku | 9^k for k empty cells | Reject a digit already present in row, column or box |
| Subset sum | 2^n subsets | Stop when the running sum exceeds the target |
| Graph coloring | k^V assignments | Reject a color used by an adjacent vertex |
| Permutation generation | n! orderings | Skip elements already used or duplicate values |
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 compared with related algorithm strategies
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.
| Strategy | Explores | Key difference from backtracking |
|---|---|---|
| Brute force | Every complete candidate | No early rejection of partial solutions |
| Depth-first search | Nodes of an explicit graph | Visits reachable nodes; backtracking adds constraint-driven pruning |
| Dynamic programming | Overlapping subproblems | Reuses stored results instead of re-exploring branches |
| Greedy algorithm | A single path of locally best choices | Never revisits a decision, so it may miss the optimum |
| Branch and bound | A tree with cost bounds | Optimization variant that prunes by cost, not only feasibility |
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.
| Requirement | Recommended approach | Reason |
|---|---|---|
| Any one valid solution | Stop at the first goal state | Avoids exploring the rest of the tree |
| All valid solutions | Record each goal and continue | Every leaf must be examined or pruned |
| Optimal solution | Branch and bound with a cost bound | Cuts branches that cannot beat the incumbent |
| Many repeated subproblems | Backtracking with memoization | Prevents recomputing identical states |
| Large constraint networks | Forward checking and propagation | Detects dead ends before descending |
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.