Interview patterns

DFS and Backtracking Explained: Choose, Explore, Undo

Updated Dec 4, 2026 · 3 min read

Backtracking is depth-first search over choices. You add one choice to a path, recurse to make the next one, then remove it on the way back so the path is clean for the next branch. Use it when a problem asks for every subset, permutation or combination, and prune a branch as soon as it breaks a rule.

DFS and Backtracking reel cover

Key points

  • ●Spot it when the problem asks for all answers and n is small, around 15 to 20.
  • ●Every call does three things: choose, explore, undo.
  • ●For 1, 2, 3 the take-or-skip tree has 8 leaves, one per subset.
  • ●Prune: return the moment a path breaks a rule, and the whole subtree is skipped.
  • ●Store path[:], a copy, never path itself.
Step-by-step visual sheet: DFS and Backtracking
The full visual sheet, made with Edithly.Open the interactive sheet

The problem that gives it away

Some problems don't want one answer. They want all of them: every subset of a list, every order of some letters, every way to place queens on a board. That word "all" is the first clue. The second is a small input, usually n up to about 15 to 20, because the number of answers itself grows like 2^n or n!. The third is a rule on the choices (no repeats, a target sum, letters that must touch on a grid) that lets you stop early.

When you see those clues, reach for DFS with backtracking. The "When to Spot It" box on the visual sheet above lists all three.

The idea: choose, explore, undo

Think of the answers as leaves of a tree. Each level of the tree is one decision. For subsets, the decision at level i is simple: take nums[i] or skip it.

Every recursive call does the same three things:

  1. Choose: add one item to the current path.
  2. Explore: recurse to make the next decision.
  3. Undo: pop the item, so the path is clean when you try the other branch.

Because you undo on the way back up, one shared list can build every answer. That's the "back" in backtracking.

The Python template

def subsets(nums):
    res, path = [], []
    def dfs(i):
        if i == len(nums):
            res.append(path[:]); return
        path.append(nums[i]); dfs(i + 1)   # take it
        path.pop(); dfs(i + 1)             # skip it
    dfs(0)
    return res

When i reaches the end, the path is one finished subset, so you store a copy. Otherwise you take nums[i], go deeper, pop it, and go deeper again without it.

Worked example: 1, 2, 3

The tree has 3 levels (take or skip 1, then 2, then 3), so it has 2^3 = 8 leaves. Taking before skipping, the template returns them in this order:

Subset Branch choices
[1, 2, 3] take 1, take 2, take 3
[1, 2] take 1, take 2, skip 3
[1, 3] take 1, skip 2, take 3
[1] take 1, skip 2, skip 3
[2, 3] skip 1, take 2, take 3
[2] skip 1, take 2, skip 3
[3] skip 1, skip 2, take 3
[] skip 1, skip 2, skip 3

That's the same table as the one on the visual sheet.

Pruning: cut a branch early

Now add a rule: the subset must sum to 4. You could build all 8 subsets and filter them, but it's faster to stop a path the moment it can't work. Since every number is positive, once the running sum passes 4 nothing below that node can fix it.

Walk the tree with that check. Take 1, take 2, take 3: the sum hits 6, so that branch returns at once. Skip 1, take 2, take 3: the sum hits 5, cut again. The only path that lands on exactly 4 is take 1, skip 2, take 3, so the only answer is [1, 3]. On 3 numbers that saves little, but the higher in the tree a cut happens, the more work it skips.

The same move shows up everywhere: Combination Sum stops when the total is too big, N-Queens stops when a queen is attacked, Word Search stops when the next letter doesn't match.

The trap: append a copy

The most common bug is res.append(path) instead of res.append(path[:]). Appending path stores a reference to the one shared list, 8 times. By the end every pop has run, that list is empty, and you return eight empty lists. The second table on the sheet shows both lines side by side.

Complexity

Subsets take O(2^n x n) time: 2^n leaves, and copying each one costs up to n. The extra space is O(n) for the recursion depth and the path, not counting the output.

LeetCode problems to practice

  • 78 Subsets
  • 46 Permutations
  • 39 Combination Sum
  • 79 Word Search
  • 51 N-Queens

Start with 78, since it's exactly the template above. Then 46 changes the choice from "take or skip" to "which unused number goes next", and 39 adds pruning on a target sum.

Frequently asked questions

What is the difference between DFS and backtracking?

DFS is the traversal: go as deep as you can before trying a sibling. Backtracking is DFS over a tree of choices where you undo each choice on the way back up, so one shared path list can build every answer.

What is the time complexity of backtracking for subsets?

O(2^n x n). There are 2^n subsets and copying each one into the result takes up to n steps. The extra space is O(n) for the recursion depth and the path.

Why do I get a list of empty lists from my backtracking code?

You appended path instead of path[:]. Every entry in the result then points to the same list, and after all the pops that list is empty. Append a copy when you reach a leaf.

When should I prune in backtracking?

As soon as the current path can no longer lead to a valid answer, for example when the running sum is already above the target. Returning early skips the whole subtree under that node.

Turn any problem or document into a visual sheet like this one

Paste a LeetCode problem, a PDF or a link into Edithly and get a step-by-step sheet you can study, share or quiz yourself on.

Make this sheet in Edithly, free