Backtracking and search
Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.
What you will be able to do
#- Model a problem as a decision tree of choices.
- Implement choose, recurse, unchoose with a shared path.
- Add pruning to cut branches that cannot succeed.
Overview
#Explore and undo
Backtracking builds a solution one choice at a time. At each step it chooses an option, recurses, then undoes the choice so the next option starts from a clean state. The shared mutable path is the key idea.
function subsets(values) {
const out = [];
const path = [];
function backtrack(index) {
if (index === values.length) {
out.push([...path]);
return;
}
path.push(values[index]);
backtrack(index + 1);
path.pop();
backtrack(index + 1);
}
backtrack(0);
return out;
}
Each value is either included or excluded, giving 2^n subsets. Copying the path when recording a result prevents later mutations from corrupting it.
The decision tree
Draw the choices as a tree. Each root-to-leaf path is one candidate solution. Backtracking is a depth-first walk of that tree, with the path variable representing the current branch.
Pruning
If a partial choice can never lead to a valid solution, stop exploring that branch. In the N-Queens problem, placing a queen in an attacked column, diagonal or row is pruned immediately, which removes huge parts of the tree. Pruning does not change the worst-case complexity but often changes real runtime dramatically.
Complexity
Backtracking is usually exponential because the decision tree is exponential. State that honestly: for subsets it is O(2^n), for permutations O(n!), for N-Queens roughly O(n!) before pruning. The value of the technique is correctness and clarity, not polynomial speed.
When not to backtrack
If subproblems overlap, dynamic programming is better because it caches shared work. If a greedy choice is provably safe, greedy is simpler. Use backtracking when you must enumerate or search a space with few valid solutions.
Practice next
- Generate all permutations of a list.
- Solve N-Queens and describe the pruning conditions.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
How many subsets does the list [1, 2, 3] have?
starter.javascript// each element is included or excludedReveal the reference answer
reference.javascriptThree elements with two choices each give 2^3 = 8 subsets, including the empty set.Authored expected output: 8
The count is two to the power of the number of elements.
Exercise 2Debug
This subset generator records references that all end up empty. Find the bug.
starter.javascriptfunction subsets(values) { const out = []; const path = []; function backtrack(i) { if (i === values.length) { out.push(path); return; } path.push(values[i]); backtrack(i + 1); path.pop(); backtrack(i + 1); } backtrack(0); return out; }Reveal the reference answer
reference.javascriptfunction subsets(values) { const out = []; const path = []; function backtrack(i) { if (i === values.length) { out.push([...path]); return; } path.push(values[i]); backtrack(i + 1); path.pop(); backtrack(i + 1); } backtrack(0); return out; }Authored expected output: Eight distinct subsets
Pushing the path array pushes a reference that is later mutated; spreading it copies the current values.
Exercise 3Explain
Explain how pruning reduces the work in N-Queens.
Reveal the reference answer
reference.textAs each queen is placed, the algorithm checks whether the square is attacked by an already placed queen along the same column or diagonal. If it is, the branch is abandoned immediately, so the algorithm never explores any completion of an invalid partial placement. This removes large subtrees and makes the search practical, though the worst case remains exponential.Authored expected output: Invalid partial placements are abandoned early, removing whole subtrees.
Pruning trades a cheap check for skipping an expensive subtree.
Common misconceptions
#- Backtracking is fast. It is exponential in general; pruning helps but does not change the class.
- You can record the path without copying it. A reference would be mutated later; copy at the point of recording.
- Backtracking and DFS are unrelated. Backtracking is DFS over a decision tree with undo.
Follow-up practice
#- dsa-from-zero-bit-manipulation
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.