Recursion & backtracking
Generate subsets, permutations and combinations.
By Invicly Tech, , in Interview Preparation. About 13 minutes to read.
In short
Recursion solves a problem by calling itself on smaller inputs until a base case. Backtracking uses recursion to build candidates step by step, undoing each choice to try the next.
Explained simply
Recursion means a function calls itself on a smaller version of the same problem. To count the people in a queue, you could ask the person in front of you: "how many people are ahead of you?" They ask the next person, and so on. The first person in line says "zero". That answer is the base case, and every answer flows back down the line.
Backtracking is recursion used to search. Think of walking through a maze. At each fork you pick a path. If it hits a dead end, you walk back to the fork and try the next path. In code, you add one choice, go deeper, and then remove that choice so you can try the next one.
Interviewers love backtracking because it covers a whole family of problems: all subsets, all orderings (permutations), all ways to reach a target sum, placing queens on a board, or finding a word in a grid. Once you know the shape, these problems feel very similar.
These searches are slow by nature, often 2^n or n! steps, so the inputs are small (usually n of 20 or less). Your job is to write the search cleanly, cut off hopeless paths early, and state the cost honestly.
Press Play on a diagram to walk through it one step at a time.
- 1Base case
Candidate complete? Record a copy and return
- 2Choose
Add one option to the current path
- 3Explore
Recurse on the remaining problem
- 4Unchoose
Remove the option to restore state
- 5Prune
Skip options that cannot lead to a valid answer
- take 1: [1]
- take 2: [1, 2]
- skip 2: [1]
- skip 1: []
- take 2: [2]
- skip 2: []
- start with 1
- 1, 2, 3
- 1, 3, 2
- start with 2
- 2, 1, 3
- 2, 3, 1
- start with 3
- 3, 1, 2
- 3, 2, 1
In depth
What the call stack really does
Each call creates a stack frame: a small block of memory holding the arguments, the local variables and the place to return to. When fact(3) calls fact(2), the fact(3) frame waits on the stack until fact(2) returns. The stack grows as you go deeper and shrinks as calls return.
The stack is limited. Python stops at about 1000 nested calls by default and raises RecursionError. Java gives each thread a fixed stack (often 512 KB to 1 MB, set with -Xss) and throws StackOverflowError when it runs out, which usually happens somewhere in the thousands to tens of thousands of frames. That is why recursion depth counts as extra space: a recursive solution that goes n levels deep uses O(n) space even if it stores nothing else.
- Every call pushes a frame; every return pops one
- Recursion depth is part of the space cost
- Deep inputs (10^5 levels) need an iterative version
- 1fact(0)
Base case: returns 1 right away
- 2fact(1)
Waiting for fact(0), then returns 1 x 1
- 3fact(2)
Waiting for fact(1), then returns 2 x 1
- 4fact(3)
Waiting for fact(2), then returns 3 x 2
- 5main
Receives 6
Three questions that define any backtracking problem
Before coding, answer three questions. What is the path (the partial answer built so far)? What are the choices at this step? When is the path complete? For subsets, the path is the chosen numbers, the choice is take or skip the next number, and it is complete when every number has been decided.
The main difference between problem types is how you avoid repeats. Combinations and subsets use a start index so you never pick an earlier element again, which stops [1, 2] and [2, 1] both appearing. Permutations care about order, so they loop over every element and use a used[] array to skip ones already in the path.
- Take or skip each item
- Record at every node or at the end
- 2^n results
- Loop from a start index
- Next call uses i + 1 (or i if reuse is allowed)
- Order does not matter
- Loop over all items
- used[] array skips taken ones
- n! results
Pruning: stop early on hopeless paths
Pruning means not exploring a branch you already know cannot succeed. It does not change the worst-case Big-O, but it often makes the real search thousands of times faster.
In Combination Sum, sort the candidates first. When a candidate is larger than the amount still needed, every later candidate is larger too, so you can break out of the loop instead of just skipping one. In N-Queens, you place one queen per row and keep three sets of blocked columns and diagonals. A cell (r, c) is on the diagonal r - c and the anti-diagonal r + c, so checking whether a square is attacked takes O(1) instead of scanning the board.
- Sort, then break when a value is too big
- Track blocked columns and diagonals in sets or boolean arrays
- Check constraints before recursing, not after
Inputs with duplicates
If the input has repeated values, such as [1, 2, 2], the plain subsets code produces [1, 2] twice. The fix is to sort the input so equal values sit next to each other, then skip a value at the same depth if it equals the one just before it: if i > start and nums[i] == nums[i - 1], continue.
The condition i > start matters. It still lets you pick the second 2 right after the first 2 on a deeper level (giving [2, 2]), but stops two sibling branches from both starting with a 2. The same trick fixes Combination Sum II and Permutations II, where for permutations you also check that the previous equal value is not currently used.
Grid backtracking: Word Search
In Word Search you look for a word by moving up, down, left and right through a letter grid, without reusing a cell. Start a search from every cell. At each step, check bounds, check the letter, then mark the cell as visited by replacing it with a symbol like #, recurse into the four neighbours, and put the letter back.
Putting the letter back is the unchoose step: without it, a failed path leaves cells blocked for later paths. The cost is O(m x n x 3^L) for a word of length L: m x n starting cells, and after the first step each cell has at most three new directions because you never go straight back. Pruning on the first wrong letter is what keeps it practical.
Learn it in 6 short steps
About 1h 20m each. Track them with a timer in your plan.
- 1Trace the call stack and base cases~1h 20m
- 2Learn the choose-explore-unchoose pattern~1h 20m
- 3Generate subsets and permutations~1h 20m
- 4Prune branches early~1h 20m
- 5Practice: Combination Sum, N-Queens~1h 20m
- 6Practice: Word Search~1h 20m
Key points
- Every recursive function needs a base case that stops further calls.
- Subsets are O(2^n) and permutations O(n!), times the cost of copying each result.
- Pruning early, such as stopping when a sum exceeds the target, saves huge work.
- Append a copy of the path; appending the path itself stores a reference that keeps changing.
Key terms
Tap a card to flip it. 0/5 known
Examples
def subsets(nums):
res, path = [], []
def backtrack(i):
if i == len(nums):
res.append(path[:]) # copy!
return
path.append(nums[i]) # choose
backtrack(i + 1) # explore
path.pop() # unchoose
backtrack(i + 1) # skip nums[i]
backtrack(0)
return res # O(n * 2^n)Combination Sum: candidates [2, 3, 6, 7], target 7
Each number may be used many times. After sorting, start with 2: left 5. Take 2 again: left 3. Take 2 again: left 1, and 2 > 1, so break. Back up and take 3 instead: left 0, record [2, 2, 3]. Back at left 5, try 3 (left 2, then 3 > 2, break), then 6 > 5, break. Back at the top, try 3, then 6, then 7: left 0, record [7]. The recursive call passes i, not i + 1, which allows reuse but never goes back to smaller numbers, so no duplicates appear.
List<List<Integer>> combinationSum(int[] c, int target) {
Arrays.sort(c);
List<List<Integer>> res = new ArrayList<>();
dfs(c, 0, target, new ArrayList<>(), res);
return res;
}
void dfs(int[] c, int start, int left, List<Integer> path, List<List<Integer>> res) {
if (left == 0) { res.add(new ArrayList<>(path)); return; }
for (int i = start; i < c.length; i++) {
if (c[i] > left) break; // sorted: the rest are bigger too
path.add(c[i]); // choose
dfs(c, i, left - c[i], path, res); // explore; i allows reuse
path.remove(path.size() - 1); // unchoose
}
}N-Queens: counting solutions for n = 4
Place one queen per row, so rows never clash. Row 0, column 0: this blocks column 0 and both diagonals. Row 1 can only use column 2 or 3. Try column 2: row 2 has no safe column, so back up. Try column 3: row 2 can use column 1, but then row 3 has nothing, so back up again, all the way to row 0. Row 0, column 1 works: queens at columns 1, 3, 0, 2. The mirror image (2, 0, 3, 1) is the second solution. For n = 8 the same code finds 92.
int count = 0; boolean[] cols, diag, anti;
int totalNQueens(int n) {
cols = new boolean[n]; diag = new boolean[2 * n]; anti = new boolean[2 * n];
place(0, n);
return count;
}
void place(int r, int n) {
if (r == n) { count++; return; }
for (int c = 0; c < n; c++) {
if (cols[c] || diag[r - c + n] || anti[r + c]) continue; // attacked
cols[c] = diag[r - c + n] = anti[r + c] = true;
place(r + 1, n);
cols[c] = diag[r - c + n] = anti[r + c] = false;
}
}Quick reference
- Subsets cost O(n x 2^n); permutations cost O(n x n!), counting the copy of each result
- Combinations: recurse with i + 1 for no reuse, with i when an item can be reused
- Duplicates: sort, then skip when i > start and a[i] == a[i - 1]
- Permutations: loop over every index and track a used[] array instead of a start index
- Sorted candidates let you break the loop as soon as one is bigger than what is left
- N-Queens: cell (r, c) sits on diagonal r - c and anti-diagonal r + c
- Python stops at about 1000 nested calls by default; Java throws StackOverflowError
- Grid search: mark a cell visited before recursing and restore it after
Common mistakes
- Missing or wrong base case, causing infinite recursion.
- Appending path instead of path[:] to results.
- Forgetting to undo a choice, leaking state into sibling branches.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Print all binary strings of length n (for n = 3: 000, 001, ..., 111) using recursion.
- Exercise 2medium
Permutations: return all orderings of a list of distinct integers.
- Exercise 3hard
Word Search: return true if a word can be formed from adjacent cells (up, down, left, right) in a letter grid, using each cell at most once.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How do I know a problem needs backtracking?
- Look for "return all" combinations, subsets, orderings or placements, or "does any arrangement exist" under constraints. Small input limits, like n up to 15 or 20, are another strong hint.
- Is recursion slower than a loop?
- Each call has a small overhead, but the Big-O is usually the same. The real risk is stack depth: very deep recursion can crash, so convert to a loop with an explicit stack when depth can reach many thousands.
- How do I state the complexity of a backtracking solution?
- Count the results or leaves of the search tree and multiply by the work per result. Subsets are O(n x 2^n) and permutations O(n x n!), because copying each answer costs O(n).
- What is the difference between recursion and backtracking?
- Recursion is the technique of a function calling itself. Backtracking is a search strategy built on recursion that makes a choice, explores, and then undoes the choice to try the next option.