Topic 6 of 21 · Intermediate
Recursion & Backtracking
Functions that call themselves, and exploring choices with undo.
Concept
A recursive function needs a base case (when to stop) and a recursive case that moves towards the base case.
Backtracking builds a solution step by step: choose, explore, then un-choose. It generates subsets, permutations and solves puzzles like N-Queens.
Each call uses a stack frame, so deep recursion costs O(depth) space.
Complexity
| Operation | Time | Space |
|---|---|---|
| Subsets of n items | O(2ⁿ · n) | — |
| Permutations of n items | O(n! · n) | — |
Code (Python)
def subsets(nums):
res, path = [], []
def dfs(i):
if i == len(nums):
res.append(path[:])
return
path.append(nums[i]) # choose
dfs(i + 1) # explore
path.pop() # un-choose
dfs(i + 1)
dfs(0)
return resRemember
- Always write the base case first.
- Copy the path when saving a result.
- Prune early to cut the search tree.
Practice these interview problems
- Subsets
- Permutations
- Combination Sum
- N-Queens
- Word Search
Lesson test
Take an 8-question test on “Recursion & Backtracking” — concepts, output prediction, bug spotting and interview questions.