Backtracking
medium 20 minBacktracking builds an answer one choice at a time and abandons a partial answer the moment it cannot work.
Check yourself
One question at a time. Each answer explains why.
Question 1 of 10
What is the core principle of backtracking?
What is pruning in backtracking?
What must you do after exploring a branch?
What is the space complexity of backtracking, apart from the output?
Which problem is NOT typically solved with backtracking?
In N-Queens, what makes a square safe for a new queen?
What is the worst-case time of backtracking for N-Queens?
A subsets function saves answers with `result.append(path)` and pops after each call. What does it return for [1, 2]?
Subset sum on sorted [2, 3, 5, 7], target 10. Where should the search backtrack?
How many complete answers does a permutations search over 4 distinct elements save?
Pick an answer to see why.
Not quite. Backtracking extends a partial solution one choice at a time and backs out as soon as it knows that partial solution cannot be completed. It is DFS with pruning.
Not quite. Pruning skips a branch the moment a check on the partial solution fails, so nothing below it is ever explored. It is what makes backtracking beat brute force.
Not quite. Unchoose: pop the path, clear the flag, remove from the set or restore the grid cell, so the next option starts from the same state.
Not quite. Only one root-to-node path exists at a time: the partial answer and d stack frames.
Not quite. Shortest paths need BFS (or Dijkstra with weights). Backtracking finds a path, or all paths, but the first one it finds need not be the shortest.
Not quite. A queen attacks along its row, column and both diagonals. Placing one queen per row handles rows; the column and diagonal checks handle the rest.
Not quite. Row 0 has n columns, row 1 at most n - 1 free ones, and so on: at most n! placements. Pruning makes the real count far smaller (2,057 calls for n = 8).
Not quite. Every entry is the same list object, and after the last pop that list is empty. Save `path[:]` to keep a snapshot.
Not quite. Going over the target can never come back down with positive numbers, so that branch is cut; with no numbers left there is nothing more to choose. Sorted input lets the over-the-target check break the whole loop.
Not quite. 4! = 4 × 3 × 2 × 1 = 24. The 16 is 2⁴, the number of subsets.
Flashcards
Say your answer, then reveal it.
Card 1 of 12
What is backtracking in one sentence?
Build a solution one choice at a time and abandon a partial solution as soon as it cannot lead to a valid one: DFS + constraint checking + undo.
Say your answer, then reveal it.
What are the moves inside every backtracking call?
Check for a complete answer; then for each option: choose it, check it (constrain), explore by recursing, and unchoose it.
Say your answer, then reveal it.
Which traversal does backtracking use, and which data structure?
Depth-first search, using a stack: usually the call stack of the recursion, sometimes an explicit one.
Say your answer, then reveal it.
What makes backtracking faster than brute force?
Pruning: it checks partial answers, so one failed check removes a whole subtree instead of testing every complete candidate.
Say your answer, then reveal it.
How many subsets and permutations do n elements have?
2ⁿ subsets (each element in or out) and n! permutations (n choices, then n - 1, ...).
Say your answer, then reveal it.
Subsets loop vs permutations loop?
Subsets: start index, only later elements. Permutations: any unused element, tracked with a used array.
Say your answer, then reveal it.
What happens when backtracking finds a solution?
It depends on the problem: return right away if one solution is enough, or save a copy and keep exploring if all solutions are needed.
Say your answer, then reveal it.
Why mark cells as visited in a maze or grid search?
So the path never steps on a cell twice: it stops infinite back-and-forth loops, and in Word Search it enforces using each cell once.
Say your answer, then reveal it.
Why try directions in a fixed order such as down, right, up, left?
It makes the search reproducible. The order can change which solution is found first, but any complete order finds a path if one exists.
Say your answer, then reveal it.
How do you check N-Queens diagonals in O(1)?
r - c is constant on one diagonal and r + c on the other. Keep sets of used columns, r - c values and r + c values.
Say your answer, then reveal it.
What does BACKTRACK stand for?
Build incrementally, Abandon invalid paths, Check constraints before recursing, Keep track of state, Try all options, Recurse deeper, Always restore state, Collect solutions at the base case, Know when to stop.
Say your answer, then reveal it.
Space complexity of backtracking?
O(d) for depth d: only the current path and its stack frames are alive at once, not the whole tree.
Say your answer, then reveal it.
These cards come back in Today, just before you would forget them.