Command Palette

Search for a command to run...

Module 13

Backtracking

Build answers one choice at a time, undo the last choice, and try the next: subsets, permutations, combinations, puzzles and grid searches.

Intermediate 4 lessons 10 problems ~55 min of lessons

Backtracking explores a tree of decisions. At each step you choose an option, explore everything that follows from it, then undo the choice so the next option starts from a clean state. It's recursion plus one discipline: always clean up after yourself.

The module gives you three templates (subsets, permutations, combinations) that cover most interview problems, then shows how to prune branches early and how to avoid duplicate answers. Expect exponential time: these problems have small inputs because the answers themselves are exponential.

Best after: Recursion

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. The base template: record every path, extend only with later elements.

  2. Duplicates in the input: sort, then skip equal values at the same depth.

  3. When order matters, any unused element can go next: track usage with a boolean array.

  4. Reusable elements (recurse with i, not i + 1) and pruning with a sorted array.

  5. One decision per position, with the options given by a lookup table: a product of choices.

  6. Prune with counts: add '(' while some remain, add ')' only when it would still be balanced.

  7. Grid backtracking: mark the cell, explore four neighbours, restore the cell.

  8. Backtracking over cut positions, choosing only cuts that leave a palindrome piece.

  9. Place one queen per row and prune with sets of used columns and diagonals for O(1) attack checks.

  10. Fill empty cells one at a time, check row/column/box constraints in O(1), and backtrack on contradictions.