Backtracking
Backtracking
Backtracking is an algorithmic technique for solving problems incrementally by building candidates one step at a time and abandoning (backtracking from) a candidate as soon as it's determined that it cannot lead to a valid solution. It's a refined form of brute force that prunes entire branches of the search space, making it far more efficient than generating all possible candidates.
How It Works
- Choose: Make a choice (place a queen, pick a number, take a path)
- Constraint check: Verify the choice doesn't violate any constraints
- Recurse: If valid, move to the next decision point and repeat
- Backtrack: If we reach a dead end (no valid choice available), undo the last choice and try the next alternative
- Base case: If all decisions have been made successfully, record the solution
The algorithm explores a decision tree using depth-first search, pruning branches that violate constraints.
The Backtracking Template
Almost every backtracking problem follows this pattern:
def backtrack(state, choices):
if is_solution(state):
record_solution(state)
return
for choice in choices:
if is_valid(state, choice):
make_choice(state, choice)
backtrack(state, remaining_choices)
undo_choice(state, choice) # backtrack
N-Queens Problem
The classic backtracking example: place N queens on an N×N chessboard so that no two queens threaten each other (no shared row, column, or diagonal).
Step-by-Step (4-Queens)
The search places one queen per row, left to right. When a column is rejected, the reason is shown in parentheses. When a row runs out of valid columns, the algorithm backtracks to the previous row and tries the next option.
Row 0: place queen at column 0
Row 1: column 0 rejected (same column)
column 1 rejected (diagonal)
column 2 placed
Row 2: columns 0-3 all rejected -> backtrack to Row 1
Row 1: column 3 placed
Row 2: column 1 placed
Row 3: columns 0-3 all rejected -> backtrack to Row 2
Row 2: no further valid column -> backtrack to Row 1
Row 1: no further valid column -> backtrack to Row 0
Row 0: place queen at column 1
Row 1: column 3 placed
Row 2: column 0 placed
Row 3: column 2 placed -> solution found
Solution: [1, 3, 0, 2] — the value at each index is the column of the
queen in that row (row 0 → column 1, row 1 → column 3, and so on).
Code Snippet
def solve_n_queens(n: int) -> list[list[int]]:
"""Find all valid N-Queens configurations.
Returns list of solutions. Each solution is a list where
solution[row] = column of the queen in that row.
"""
solutions = []
queens = [] # queens[i] = column of queen in row i
# Track attacked columns and diagonals for O(1) constraint checking
columns = set()
diag_positive = set() # row + col (identifies / diagonals)
diag_negative = set() # row - col (identifies \ diagonals)
def backtrack(row: int) -> None:
if row == n:
solutions.append(queens[:])
return
for col in range(n):
# Check if this position is under attack
if col in columns:
continue
if (row + col) in diag_positive:
continue
if (row - col) in diag_negative:
continue
# Make choice
queens.append(col)
columns.add(col)
diag_positive.add(row + col)
diag_negative.add(row - col)
# Recurse to next row
backtrack(row + 1)
# Undo choice (backtrack)
queens.pop()
columns.remove(col)
diag_positive.remove(row + col)
diag_negative.remove(row - col)
backtrack(0)
return solutions
More Examples
Generate All Permutations
def permutations(nums: list[int]) -> list[list[int]]:
"""Generate all permutations of the input list."""
result = []
used = [False] * len(nums)
current = []
def backtrack() -> None:
if len(current) == len(nums):
result.append(current[:])
return
for i in range(len(nums)):
if used[i]:
continue
used[i] = True
current.append(nums[i])
backtrack()
current.pop()
used[i] = False
backtrack()
return result
Subset Sum
def subset_sum(numbers: list[int], target: int) -> list[list[int]]:
"""Find all subsets that sum to target."""
result = []
current = []
def backtrack(index: int, remaining: int) -> None:
if remaining == 0:
result.append(current[:])
return
if remaining < 0 or index >= len(numbers):
return
# Include numbers[index]
current.append(numbers[index])
backtrack(index + 1, remaining - numbers[index])
current.pop()
# Exclude numbers[index]
backtrack(index + 1, remaining)
backtrack(0, target)
return result
Complexity Analysis
Time Complexity: O(n!)
For the N-Queens problem:
- Row 0 has n choices
- Row 1 has at most n-1 valid choices (one column blocked)
- Row 2 has at most n-2 valid choices
- Total: approximately n × (n-1) × (n-2) × ... = O(n!)
In practice, pruning eliminates many branches early, so the actual number of nodes explored is much less than n!. For 8-Queens, instead of checking all 8^8 = 16 million placements, backtracking explores only about 15,000 nodes.
Space Complexity: O(n)
The recursion depth is at most n (one level per row/decision). The constraint tracking sets use O(n) space. Total auxiliary space is O(n).
Backtracking vs. Brute Force
| Approach | Strategy | N-Queens (n=8) |
|---|---|---|
| Brute Force | Try all n^n placements | 16,777,216 checks |
| Backtracking | Prune invalid branches early | ~15,000 nodes |
Backtracking's power is in early pruning. As soon as a partial solution violates a constraint, the entire subtree is skipped.
When to Use Backtracking
- Constraint satisfaction: Sudoku, crossword puzzles, graph coloring.
- Combinatorial search: Permutations, combinations, subsets.
- Optimization with constraints: Find best solution among valid candidates (e.g., knapsack).
- Puzzle solving: N-Queens, mazes, word search, cryptarithmetic.
- Game trees: Chess/checkers move exploration (with alpha-beta pruning).
When to Avoid It
- Greedy works: If a greedy algorithm gives the optimal solution, it's faster than exploring all branches.
- Dynamic programming applies: If subproblems overlap, DP avoids redundant computation.
- No constraints to prune: If every branch must be explored anyway, backtracking degenerates to brute force.
- Tight time limits: For very large n, even pruned backtracking may be too slow. Consider approximation algorithms.
Optimization Techniques
- Constraint propagation: Maintain sets of valid choices to prune faster.
- Variable ordering: Choose the most constrained variable first (most restricted row/column).
- Symmetry breaking: Avoid exploring mirror/rotated solutions (reduces work by up to 8x for N-Queens).
- Memoization: Cache explored states if the same subproblem can be reached via different paths.
Key Properties
| Property | Value |
|---|---|
| Paradigm | Exhaustive search with pruning |
| Explores | Decision tree (DFS) |
| Pruning | Yes — skips invalid branches |
| Guarantees optimal | Yes (finds all/best solutions) |
| Time | Exponential worst case (O(n!) or O(2^n)) |