AlgoViz

Backtracking

medium 20 min

Backtracking builds an answer one choice at a time and abandons a partial answer the moment it cannot work.

See it run

Choose, explore, unchoose: watch the search walk a tree of decisions, cut dead branches early and back up to try the next option.

Operations

Subsets of [1, 2, 3]

Build every subset by choosing which number comes next, always from the numbers after the last one. Every node of this tree is an answer, so the search saves the path the moment it arrives.

Step 1 of 8

Start with the empty path

[ ]#1

result: [ ]

The path is []. Before trying anything, backtrack(0) saves a copy of it: the empty set is a subset too. That is answer #1.

Step 1: Start with the empty path

def subsets(nums):    result = []    path = []    def backtrack(start):        result.append(path[:])          # every node is an answer: save a copy        for i in range(start, len(nums)):            path.append(nums[i])        # choose            backtrack(i + 1)            # explore: only later numbers            path.pop()                  # unchoose    backtrack(0)    return result
Time
O(n · 2ⁿ)
Space
O(n) path and stack
subsets of 3
2³ = 8
subsets of 10
1,024
recursion depth
n

The start index is the whole trick for subsets and combinations: only look forward, and each set is built exactly once.

In the real world

The same backtracking doing real jobs. Pick one and step through it.

A mouse starts at the top-left corner and wants the cheese at the bottom-right. At every cell it tries down, right, up, left in that order, never steps on a wall or a cell it has already visited, and backs up when it is stuck.

Step 1 of 6

Start at S

01234
0S█
1██
2█
3██
4█E

path length 1

The mouse stands on S at (0, 0) and marks it as visited. Walls are the dark blocks; E is the exit.

Step 1: Start at S

def solve(maze, r=0, c=0, path=None, seen=None):    path = path if path is not None else [(0, 0)]    seen = seen if seen is not None else {(0, 0)}    if (r, c) == (len(maze) - 1, len(maze[0]) - 1):        return list(path)    for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]:   # down, right, up, left        nr, nc = r + dr, c + dc        if 0 <= nr < len(maze) and 0 <= nc < len(maze[0]) and not maze[nr][nc] and (nr, nc) not in seen:            seen.add((nr, nc)); path.append((nr, nc))    # choose            found = solve(maze, nr, nc, path, seen)      # explore            if found:                return found            path.pop()                                   # unchoose (cell stays seen)    return None

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Forgetting to unchoose

    critical

    Without the undo, the choice from one branch leaks into the next. The path keeps growing, used flags stay True, and later answers are wrong or missing.

    Wrong
    for x in options:    path.append(x)    backtrack(path)    # forgot path.pop(): the next x is added on top of this one
    Right
    for x in options:    path.append(x)      # choose    backtrack(path)     # explore    path.pop()          # unchoose
  • Saving the path itself, not a copy

    critical

    result.append(path) stores a reference to the one list that keeps changing. When the search ends the path is empty, so every saved answer is an empty list.

    Wrong
    if len(path) == n:    result.append(path)        # all entries end up as the same (empty) list
    Right
    if len(path) == n:    result.append(path[:])     # or list(path) / path.copy()
  • No return after a complete answer

    major

    When the base case saves an answer but does not return, the code keeps choosing past a full solution. That gives duplicates, answers that are too long, or index errors.

    Wrong
    if total == target:    result.append(path[:])# falls through and keeps adding numbers
    Right
    if total == target:    result.append(path[:])    return                    # this branch is finished
  • Pruning after the choice instead of before

    major

    Choosing first and checking inside the next call works, but every invalid branch still costs a call and an undo. Checking before choosing skips it entirely, and with sorted input a single check can break the whole loop.

    Wrong
    for i in range(start, len(nums)):    path.append(nums[i])    backtrack(i + 1, total + nums[i])   # the call then sees total > target    path.pop()
    Right
    for i in range(start, len(nums)):    if total + nums[i] > target:        break                           # sorted: nothing later fits either    path.append(nums[i])    backtrack(i + 1, total + nums[i])    path.pop()
  • Duplicates in the input

    major

    With nums = [1, 2, 2], choosing the first 2 or the second 2 at the same level builds the same subset twice. Sort, then skip a number equal to the one before it at the same level.

    Wrong
    for i in range(start, len(nums)):    path.append(nums[i])      # [1, 2] appears twice    backtrack(i + 1)    path.pop()
    Right
    nums.sort()for i in range(start, len(nums)):    if i > start and nums[i] == nums[i - 1]:        continue              # same value already tried at this level    path.append(nums[i])    backtrack(i + 1)    path.pop()
  • Marking a grid cell and never restoring it

    minor

    In Word Search, a cell marked # must get its letter back when the call returns. Otherwise the next start cell searches a damaged grid and misses words that are really there.

    Wrong
    board[r][c] = "#"found = dfs(r + 1, c, k + 1) or dfs(r, c + 1, k + 1)return found                  # the letter is lost
    Right
    saved, board[r][c] = board[r][c], "#"found = dfs(r + 1, c, k + 1) or dfs(r, c + 1, k + 1)board[r][c] = saved           # restore before returningreturn found

Interview tips

  • How to explain it

    • Backtracking is depth-first search over a tree of choices, with a check that abandons a partial answer as soon as it cannot work.
    • At each step: choose an option, explore with it, then unchoose to restore the state.
    • Time is about b^d nodes, b options per step and d steps; space is O(d) for the current path.
  • During the interview

    • Ask whether you need all solutions, one solution, or just a count.
    • Ask about duplicates in the input: that changes the template.
    • Draw a small decision tree for n = 3 before writing code.
    • Name the pattern: subsets, permutations, constraints, partitioning or grid search.
  • Memory tricks

    • Try it, check it, undo it, move it.
    • Subsets look forward (start index); permutations look everywhere (used array).
    • 2ⁿ for in-or-out, n! for arrange-them-all.
  • Watch out

    • Copy the path when you save it.
    • Undo every change: the path, used flags, sets and grid marks.
    • For shortest paths use BFS; for overlapping subproblems use dynamic programming.