Backtracking
Backtracking Fundamentals
Master Backtracking foundations: state space trees, recursive pruning conditions, choice trees, and complexity metrics.
Last Updated: August 2, 2026
•
15 min read
1. Introduction
What is Backtracking?
Backtracking is a systematic search strategy that explores all configurations of a problem space recursively. It is basically a refined Depth-First Search (DFS) over a virtual State Space Tree:Why study it?
Unlike brute-force enumeration, backtracking prunes vast subtrees of invalid choices early. It is a critical topic in technical interviews, modeling problems like permutations, puzzle solvers (Sudoku, N-Queens), and grid pathfinding.2. Mental Model: The Chalk-Marked Maze
Imagine trying to find your way out of a complex maze:
3. The Core Backtracking Template
All backtracking algorithms follow a standardized recursive template:
4. Visualizing the State Space Tree
Below is the state space tree for generating permutations of [1, 2]:
[1, 2], it's added to the results.2), returns to node Choose 1, pops 1, returns to the Root, and tries the other branch starting with 2.5. Real-World Examples
6. Interview Perspective
How Interviewers Ask This Topic
Interviewers evaluate code lifecycle hygiene:Common Mistakes
Warning: 1. Forgetting to Undo State (No Backtracking): Leaving indicators in global sets/arrays marked after returning. In the template, if you add an element to
currentPath or set used[i] = true, you MUST remove/unset them after the recursive call, otherwise subsequent search branches will receive corrupted state variables.> 2. Copying Objects repeatedly: Creating new list copies during every recursive call (e.g. backtrack(new ArrayList<>(path))). This introduces high GC allocation overhead. Keep a single path instance and make copies only when adding to the final results.
7. Summary
O(2^N) or factorially O(N!) based on branches.8. Quiz
Question 1: What occurs if you forget to copy currentPath when adding it to results: results.add(currentPath)?
Answer: All items in the final results list will be empty (or identical). SincecurrentPath is passed by reference, any future pops and deletes will mutate the reference inside the results list. Always add a copy: results.add(new ArrayList<>(currentPath)).
Question 2: What is the space complexity of a backtracking algorithm with recursion tree height H?
Answer:O(H) space, matching the maximum height of the system call recursion stack.