AlgoViz

Subsets

medium 22 min

Generating every subset is the first backtracking pattern most interviews ask for, and there are four standard ways to write it: take-or-skip recursion, a start-index loop, iterative cascading and bitmask counting.

See it run

Five ways to write every subset of [1, 2, 3], and the sort-and-skip rule that keeps duplicates out of Subsets II.

Operations

Take or skip [1, 2, 3]

One decision per number: take it or skip it. The recursion makes a full binary tree of depth n, and only the leaves, where every number has been decided, are answers.

Step 1 of 8

Index 0, nothing decided

∅

i = 0 · path ∅

dfs(0) stands before the first number with an empty path. It has exactly two moves: take 1 or skip 1. Each node below shows the subset built so far, with \varnothing for empty.

Step 1: Index 0, nothing decided

def subsets(nums):    result, path = [], []    def dfs(i):        if i == len(nums):            result.append(path[:])      # a leaf: every number decided            return        path.append(nums[i])            # take nums[i]        dfs(i + 1)        path.pop()                      # undo the take        dfs(i + 1)                      # skip nums[i]    dfs(0)    return result
Time
O(n · 2ⁿ)
Space
O(n) path and stack
leaves (answers)
2³ = 8
calls in total
2⁴ - 1 = 15
depth
n = 3

This is the shape to reach for when each element carries its own decision: Subsets II's skip-all-copies rule, target sums and knapsack all start here.

In the real world

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

Three things on the bed: a shirt (S), pants (P) and a hat (H). For each one you decide take or leave. Every way of packing is a path through the take-or-leave tree.

Step 1 of 5

The shirt: take or leave

∅S∅

2 ways

Start with an empty suitcase. The first decision is the shirt: take it (left) or leave it (right). Two possible suitcases so far.

Step 1: The shirt: take or leave

items = ["shirt", "pants", "hat"]def pack(i, bag):    if i == len(items):        print(bag or "empty suitcase")        return    pack(i + 1, bag + [items[i]])   # take it    pack(i + 1, bag)                # leave itpack(0, [])   # prints all 8 ways to pack

Common mistakes

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

  • Saving the path, not a copy

    critical

    path is one list that keeps changing. Appending it stores a reference, so after the last pop every saved entry is the same empty list.

    Wrong
    result.append(path)        # every entry is the same list object
    Right
    result.append(path[:])     # a snapshot; list(path) or path.copy() also work
  • Looping from 0 instead of start

    critical

    Starting at 0 lets a later call pick an earlier number again, so [1, 2] and [2, 1] both appear, and numbers can repeat inside one subset. The start index is what makes order not matter.

    Wrong
    for i in range(len(nums)):        # looks backwards too    path.append(nums[i])    backtrack(i + 1)    path.pop()
    Right
    for i in range(start, len(nums)):  # only later numbers    path.append(nums[i])    backtrack(i + 1)    path.pop()
  • An append with no matching pop

    critical

    Without the undo, the number chosen in one branch leaks into the next. In take-or-skip it means the skip branch still contains the number, so every subset is wrong.

    Wrong
    path.append(nums[i])dfs(i + 1)dfs(i + 1)          # "skip" branch still has nums[i] in path
    Right
    path.append(nums[i])dfs(i + 1)path.pop()          # every append needs a popdfs(i + 1)
  • Losing the empty subset

    major

    The empty set is always a subset. Starting the mask loop at 1, or saving only when the path is non-empty, returns 2ⁿ - 1 answers and fails the test for [].

    Wrong
    for mask in range(1, 1 << n):     # skips mask 0    ...if path:                           # skips []    result.append(path[:])
    Right
    for mask in range(1 << n):        # 0 is the empty set    ...result.append(path[:])             # save every node, empty included
  • Subsets II: i > 0 instead of i > start

    major

    The skip must only apply to the same level of the tree. i > 0 also blocks the second copy when it comes straight after the first one level deeper, so [2, 2] and [1, 2, 2] go missing. Forgetting to sort breaks it too: the copies are not neighbours, so the check never sees them.

    Wrong
    for i in range(start, len(nums)):    if i > 0 and nums[i] == nums[i - 1]:        continue          # also blocks [2, 2]
    Right
    nums.sort()for i in range(start, len(nums)):    if i > start and nums[i] == nums[i - 1]:        continue          # only repeats at this level
  • Growing the list you are looping over

    minor

    In the cascading version, appending to result while iterating over it means the loop keeps reaching the subsets it just made, and it never ends. Build the new subsets from a snapshot first.

    Wrong
    for x in nums:    for s in result:        result.append(s + [x])     # infinite loop
    Right
    for x in nums:    result += [s + [x] for s in result]   # list built before it is added

Interview tips

  • How to explain it

    • Every element is either in or out, so there are 2ⁿ subsets and the output alone costs O(n · 2ⁿ).
    • Name the shape: take-or-skip (answers at the leaves) or start-index (every node is an answer).
    • Mention the iterative and bitmask versions as alternatives, and when each fits.
  • During the interview

    • Ask whether the input can contain duplicates and whether the output order matters.
    • Draw the tree for [1, 2, 3] before coding; it takes thirty seconds and catches loop-bound bugs.
    • Check n: up to about 20 is fine for 2ⁿ; much more means the problem wants DP or maths, not enumeration.
  • Memory tricks

    • FAIS: Forward only, Add every path, Include the element, Subtract it after.
    • Light switches: one switch per element, 2ⁿ ways to set them, and the switches read as a binary number.
    • Duplicates: sort, then skip a repeat only if it is not the first in its loop.
  • Watch out

    • Copy the path when you save it.
    • Loop from start, not 0, and pop after every recursive call.
    • Keep the empty set: mask 0 and the root call both produce it.