DSA Notes
Master backtracking — the algorithmic technique for finding all solutions by recursively exploring choices and undoing them when they lead to dead ends. Learn the backtracking template, pruning strategies, and classic examples: N-Queens, Sudoku solver, and combination sum.
What Is Backtracking?
Backtracking is a recursive algorithm that explores all possible solutions by making a choice, recursing forward, and then undoing the choice (backtracking) if it leads to a dead end or an invalid state.
The key insight: backtracking is like exploring a maze. At each junction, you pick a path. If you reach a dead end, you return to the last junction and try a different path. This "try and undo" is the defining characteristic of backtracking.
Example 1 — Subsets (All Subsets of an Array)
Decision tree:
| Choose 1 | backtrack(1, [1]) |
| Choose 2 | backtrack(2, [1,2]) |
| Choose 3: backtrack(3, [1,2,3]) | save [1,2,3] |
| Undo 2 | save [1,2] |
| Choose 3: backtrack(3, [1,3]) | save [1,3] |
| Undo 1 | save [1] |
| Choose 2 | backtrack(2, [2]) |
Example 2 — Combination Sum
Problem: Find all combinations from candidates that sum to target. Can reuse elements.
Example 3 — N-Queens
Problem: Place N queens on an N×N chessboard so no two queens attack each other.
Example 4 — Sudoku Solver
Pruning — Making Backtracking Efficient
Without pruning, backtracking explores all possible states. Pruning cuts branches that cannot lead to valid solutions:
Complexity of Backtracking
Backtracking is exponential in the worst case, but pruning can dramatically reduce actual runtime.
| Problem | Worst Case | With Pruning |
|---|---|---|
| Subsets | O(2ⁿ) | O(2ⁿ) (must enumerate all) |
| Permutations | O(n!) | O(n!) (must enumerate all) |
| N-Queens | O(n!) | ~O(n!) but much better in practice |
| Sudoku | O(9^81) | O(1) to O(9^81) depending on puzzle |
| Combination Sum | O(2^t) | Much less with sorted + break |
Summary
Backtracking = recursion + "undo" on backtrack:
- Choose: Make a decision at the current step
- Explore: Recurse with the new state
- Undo: Remove the choice (restore previous state)
- Prune: Skip invalid or unpromising choices early
Template applies to:
- Finding all solutions (permutations, subsets, combinations)
- Constraint satisfaction (N-Queens, Sudoku, crossword)
- Path finding in graphs with constraints
*Recursion folder complete. Next: Searching — Linear Search*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Backtracking Introduction — The Recursive Exploration with Undo.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, recursion, backtracking, introduction
Related Data Structures & Algorithms Topics