Backtracking
Also Known As
constraint satisfaction
pruning
depth-first search
TL;DR
An algorithmic technique that builds solutions incrementally, abandoning a path ('backtracking') when it determines the current path cannot lead to a valid solution.
Explanation
Backtracking is a refined brute force: try a candidate, check constraints, recurse, and undo the choice if it leads to a dead end. Classic problems: N-Queens, Sudoku solver, permutations/combinations, maze solving, and constraint satisfaction. The key insight: pruning invalid branches early avoids exploring the full exponential search space. Backtracking is the basis for many combinatorial optimisation algorithms.
Common Misconception
✗ Backtracking is just brute force — backtracking prunes invalid branches early, often reducing the actual search space by orders of magnitude compared to exhaustive enumeration.
Why It Matters
Backtracking solves constraint satisfaction problems (scheduling, configuration validation, puzzle solving) that are impractical with brute force enumeration.
Common Mistakes
- Not undoing state changes when backtracking — the undo step is as important as the do step.
- Pruning too aggressively — checking invalid constraints costs time; only prune when the check is cheap relative to the avoided search.
- Using backtracking when dynamic programming applies — overlapping subproblems are better solved with DP.
- No early termination when the first valid solution is found — continue searching unnecessarily.
Code Examples
✗ Vulnerable
// Brute force permutations — generates all then filters:
function permutations(array $arr): array {
if (count($arr) <= 1) return [$arr];
$result = [];
foreach ($arr as $i => $val) {
$rest = array_values(array_filter($arr, fn($k) => $k !== $i, ARRAY_FILTER_USE_KEY));
foreach (permutations($rest) as $perm) $result[] = array_merge([$val], $perm);
}
return $result; // Generates all n! then caller filters — wasteful
}
✓ Fixed
// Backtracking Sudoku solver — prunes invalid choices early:
function solveSudoku(array &$board): bool {
foreach ($board as $r => $row) {
foreach ($row as $c => $cell) {
if ($cell !== 0) continue;
for ($num = 1; $num <= 9; $num++) {
if (isValid($board, $r, $c, $num)) {
$board[$r][$c] = $num;
if (solveSudoku($board)) return true; // Recurse
$board[$r][$c] = 0; // Backtrack — undo the choice
}
}
return false; // No valid number — backtrack further
}
}
return true; // All cells filled
}
References
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
15 Mar 2026
Edited
22 Mar 2026
Views
26
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Perplexity 9
Amazonbot 6
Google 2
Unknown AI 2
SEMrush 2
Ahrefs 1
How they use it
crawler 21
crawler_json 1
Related categories
⚡
DEV INTEL
Tools & Severity
🟢 Low
⚙ Fix effort: High
⚡ Quick Fix
Add explicit base cases and prune branches early — backtracking without pruning is just brute force; validate partial solutions before recursing deeper
📦 Applies To
any
web
cli
🔗 Prerequisites
🔍 Detection Hints
Exhaustive search without pruning; permutation generation O(n!) without early exit; PHP timeout on backtracking algorithm with large input
Auto-detectable:
✗ No
xdebug
blackfire
⚠ Related Problems
🤖 AI Agent
Confidence: Low
False Positives: High
✗ Manual fix
Fix: High
Context: Function
Tests: Update