Courses / DSA Patterns for Working Engineers / Chapter 13
Module 4 · Binary search, subsets, greedy, backtracking and DP · Chapter 13 of 39
Backtracking: Choose, Explore, Undo and Prune
Builds on Subsets: Every Subset, Permutation and Combination. Next up: Dynamic Programming: States, Transitions and Tables.
Part 1 · Introduction to backtracking
Choose, explore, undo
A walker in a maze who reaches a dead end steps back to the last junction and tries another path. Backtracking does the same with partial answers.
Backtracking builds a solution one decision at a time. After each decision it explores what can follow, and when that path is finished or has failed, it undoes the decision and tries the next option. The search is depth first over a tree of decisions: each node is a partial solution, and each edge is one more choice.
The subsets chapter generated every subset and every order. Backtracking is the same walk with two additions. A rule can reject a partial solution early, and the problem can ask for solutions that satisfy constraints, not merely for all of them.
Every backtracking function follows the same three steps inside a loop over the options.
- Choose: change the shared state to include the option, for example push a value onto the partial answer.
- Explore: call the same function for the next decision.
- Undo: change the state back, exactly, for example pop the value.
The undo step is what makes one shared array enough. Without it you would copy the whole partial answer at every node, which costs time and memory at every step of the tree.