Backtracking
Data Structures & Algorithms · Backtracking · Advanced · 16 min
Explore every choice, undo, try the next: subsets, permutations, puzzles.
A tree of forks in a path. At every fork you either pick up the next item or walk past it. You explore one branch all the way to the end, then walk back to the last fork and try the other way. Every route from the top to the bottom is one subset.
The idea in everyday words
Walking through a maze: at each fork, pick a path. Dead end? Walk BACK to the last fork and try the next path. Backtracking = recursion + 'undo my last move'.
The template
def backtrack(path, choices):
if done: record(path); return
for choice in choices:
path.append(choice) # choose
backtrack(path, ...) # explore
path.pop() # un-choose (backtrack!)
All subsets: include or skip each item
For every item you make 2 choices → 2ⁿ subsets. Run it and see:
def subsets(nums):
result = []
def go(i, path):
if i == len(nums):
result.append(path[:])
return
path.append(nums[i]); go(i + 1, path); path.pop() # take it
go(i + 1, path) # skip it
go(0, [])
return result
print(subsets([1, 2, 3]))
Permutations
def perms(items, path=[]):
if not items:
print(path)
return
for i in range(len(items)):
perms(items[:i] + items[i + 1:], path + [items[i]])
perms(["a", "b", "c"])
Pruning: stop exploring early when a path can't work (e.g. sum already too big). It makes backtracking practical.
Step by step
- [] :
take 1 → [1]
- [1]:
take 2 → [1,2] → take 3 → [1,2,3] ✓ record
- undo 3:
skip 3 → [1,2] ✓ record
- undo 2:
skip 2 → [1] → take 3 → [1,3] ✓ …
Code example
def combo_sum(nums, target):
out = []
def go(start, path, total):
if total == target:
out.append(path[:]); return
if total > target:
return # prune
for i in range(start, len(nums)):
path.append(nums[i])
go(i, path, total + nums[i])
path.pop()
go(0, [], 0)
return out
print(combo_sum([2, 3, 6, 7], 7))Complexity
- Time: O(2ⁿ) to count subsets (O(n·2ⁿ) to list them, because each copy costs up to n), O(n·n!) for permutations
- Space: O(n) recursion depth (plus the answers you store)
Interview tips
Subsets, Permutations, Combination Sum, N-Queens, Word Search.
Mention pruning to show optimisation thinking.
Challenge: Count Subsets With Target Sum
Return how many subsets of nums add up exactly to target (the empty subset counts if target is 0).
Example: count_subsets([1, 2, 3], 3) → 2 ({1,2} and {3})
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Subsets (Medium)
- Permutations (Medium)
- Combination Sum (Medium)
- Target Sum (Medium)
More in Backtracking
Previous: Beyond Comparison Sorts · Next: Topological Sort & DAGs