← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Backtracking

algorithms Advanced

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
}

Added 15 Mar 2026
Edited 22 Mar 2026
Views 26
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 2 pings F 0 pings S 0 pings S 0 pings M 0 pings T 1 ping W 0 pings T 1 ping F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Perplexity 9 Amazonbot 6 Google 2 Unknown AI 2 SEMrush 2 Ahrefs 1
crawler 21 crawler_json 1
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

✓ schema.org compliant