{
    "slug": "backtracking",
    "term": "Backtracking",
    "category": "algorithms",
    "difficulty": "advanced",
    "short": "An algorithmic technique that builds solutions incrementally, abandoning a path ('backtracking') when it determines the current path cannot lead to a valid solution.",
    "long": "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.",
    "aliases": [
        "constraint satisfaction",
        "pruning",
        "depth-first search"
    ],
    "tags": [
        "algorithms",
        "recursion",
        "optimisation"
    ],
    "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."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "recursion_patterns",
        "dynamic_programming",
        "graph_algorithms",
        "big_o_notation"
    ],
    "prerequisites": [
        "recursion_patterns",
        "dynamic_programming",
        "graph_algorithms"
    ],
    "refs": [
        "https://en.wikipedia.org/wiki/Backtracking"
    ],
    "bad_code": "// Brute force permutations — generates all then filters:\nfunction permutations(array $arr): array {\n    if (count($arr) <= 1) return [$arr];\n    $result = [];\n    foreach ($arr as $i => $val) {\n        $rest = array_values(array_filter($arr, fn($k) => $k !== $i, ARRAY_FILTER_USE_KEY));\n        foreach (permutations($rest) as $perm) $result[] = array_merge([$val], $perm);\n    }\n    return $result; // Generates all n! then caller filters — wasteful\n}",
    "good_code": "// Backtracking Sudoku solver — prunes invalid choices early:\nfunction solveSudoku(array &$board): bool {\n    foreach ($board as $r => $row) {\n        foreach ($row as $c => $cell) {\n            if ($cell !== 0) continue;\n            for ($num = 1; $num <= 9; $num++) {\n                if (isValid($board, $r, $c, $num)) {\n                    $board[$r][$c] = $num;\n                    if (solveSudoku($board)) return true; // Recurse\n                    $board[$r][$c] = 0; // Backtrack — undo the choice\n                }\n            }\n            return false; // No valid number — backtrack further\n        }\n    }\n    return true; // All cells filled\n}",
    "quick_fix": "Add explicit base cases and prune branches early — backtracking without pruning is just brute force; validate partial solutions before recursing deeper",
    "severity": "low",
    "effort": "high",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/backtracking",
        "html_url": "https://codeclaritylab.com/glossary/backtracking",
        "json_url": "https://codeclaritylab.com/glossary/backtracking.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Backtracking](https://codeclaritylab.com/glossary/backtracking) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/backtracking"
            }
        }
    }
}