Recursion & Backtracking · Lesson
Recursion and backtracking, explained: the template and every pattern
Learn recursion and backtracking: base cases, pick / not-pick, permutations, N-Queens and grid search, with templates in Java, Python, C++ and JavaScript.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
What recursion is
A recursive function solves a problem by calling itself on a smaller version of the same problem. It needs two things: a base case that stops, and a step that moves toward it. fact(n) = n * fact(n - 1) with fact(0) = 1 is the whole idea.
Each call waits on the call stack until the smaller call returns. Calls go down to the base case, and answers are combined on the way back up. The stack depth is the extra space a recursion uses.
Backtracking: choose, explore, un-choose
Backtracking is recursion that builds an answer one choice at a time. At each step you try a choice, recurse to make the next one, then undo the choice and try the next. The calls form a tree, and every leaf is one finished (or rejected) answer.
Every backtracking problem fills in the same four blanks:
- State: what you have built so far (a path, a board, a sum).
- Complete: when the state is a full answer. Record a copy of it.
- Choices: what you can add next (take or skip this item, any unused item, any letter for this digit).
- Prune: which choices are invalid or cannot lead anywhere, so you skip their whole subtree.
Why it is slow, and how to make it fast enough
The cost is roughly (number of nodes in the choice tree) × (work per node). Subsets give 2^n leaves, permutations n!. That is fine for n up to about 10 to 20, which is exactly what these problems allow.
Pruning is what makes hard searches finish: stop when the sum is already too big, when a queen is attacked, or when the remaining items cannot fill a bucket. If the same state is reached many times, add memoisation and you have dynamic programming.
What it costs
| Operation | Time | Space |
|---|---|---|
| All subsets of n items | O(n · 2^n) | O(n) |
| All permutations of n items | O(n · n!) | O(n) |
| All combinations of k from n | O(k · C(n, k)) | O(k) |
| N-Queens (with pruning) | O(n!) | O(n) |
| Word search on an m × n grid, word length L | O(m · n · 3^L) | O(L) |
| Meet in the middle on n items | O(n · 2^(n/2)) | O(2^(n/2)) |
Built into your language
List<Integer> path = new ArrayList<>();
path.add(3); // choose
path.remove(path.size() - 1); // un-choose: remove by index, not by value
List<Integer> copy = new ArrayList<>(path); // record a copy, never path itself
StringBuilder sb = new StringBuilder("ab");
sb.append('c'); sb.deleteCharAt(sb.length() - 1); // choose / un-choose on a string
Collections.swap(path, 0, 0); // swap two positions in a list path = []
path.append(3) # choose
path.pop() # un-choose
res.append(path[:]) # record a copy, never path itself
from itertools import combinations, permutations, product
list(combinations([1, 2, 3], 2)) # [(1, 2), (1, 3), (2, 3)]
list(permutations([1, 2, 3])) # all 6 orders
list(product("ab", repeat=2)) # one choice per position: aa ab ba bb
import sys
sys.setrecursionlimit(10_000) # the default limit is about 1000 frames vector<int> path;
path.push_back(3); // choose
path.pop_back(); // un-choose
res.push_back(path); // push_back copies the vector
vector<int> a = {1, 2, 3}; // must start sorted to see every order
do { /* use a */ } while (next_permutation(a.begin(), a.end()));
swap(a[0], a[2]); const path = [];
path.push(3); // choose
path.pop(); // un-choose
res.push([...path]); // record a copy, never path itself
// strings are immutable: pass s + ch down and nothing needs undoing
function go(s) { if (s.length === 2) return; go(s + "a"); go(s + "b"); } Mistakes everyone makes
- Adding the shared
pathto the result instead of a copy: every saved answer ends up as the same (empty) list. - Forgetting to undo a choice after the recursive call, so the next branch starts from the wrong state.
- Skipping duplicates at every depth instead of only among siblings (
i > start, noti > 0). - A base case that is never reached: the recursive step must always make the problem smaller.
- Deep recursion in Python hits the default limit of about 1000 frames: raise it or write the loop iteratively.
The 9 patterns, in order
Each one: the idea and template, its variations with a worked example, then problems for you to solve.
- 1 Basic recursion: base cases, structures and paths Write the answer in terms of a smaller version of the same problem, and stop at a base case. The same habit walks trees and nested lists, and with an undo step it becomes the backtracking template. 4 variations · 8 problems
- 2 N-Queens: place one queen per row Every row holds exactly one queen, so place them row by row. Three boolean arrays for columns and both diagonals tell you in O(1) whether a square is safe. 1 variation · 1 problem
- 3 Pick / not-pick: subsets, combinations and sums For each item, either take it or skip it. That binary choice generates every subset; a start index, a target and a duplicate rule turn it into combinations, combination sums and bucket filling. 5 variations · 12 problems
- 4 Permutations: every order of the items Fill position by position with an item not used yet. Either swap candidates into place or keep a used array; for duplicates, sort and only use the first unused copy of each value. 3 variations · 4 problems
- 5 Grid backtracking: paths and boards On a grid, the choice is which neighbour to step to or which value to write in a cell. Mark the cell, recurse, and restore it, so other paths can use it again. 3 variations · 5 problems
- 6 Choice per position: menus and cuts Fill the answer slot by slot, where each slot has its own menu of options: the letters of a digit, the next piece of a string, or the block that fits on top of two others. 4 variations · 9 problems
- 7 Divide and conquer: split, solve, combine Split the input into independent parts, solve each part recursively, then combine the answers. Unlike backtracking, nothing is undone: each call returns its result to the caller. 2 variations · 2 problems
- 8 Digit-by-digit construction Build each number one digit at a time, where the next digit depends on the last one. You only ever create valid numbers, instead of scanning every number in the range. 1 variation · 1 problem
- 9 Meet in the middle: two half-sized searches When 2^n is too many but 2^(n/2) is fine, split the items in half, list every subset sum of each half, sort one side and binary search it for the best partner of each sum on the other side. 1 variation · 1 problem