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.

Video lesson · Chapter 1 of 9

Three sound switches

0:00 / 6:48

Subsets in 75 seconds

1:26Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Decide each element. Every element is in or out: take-or-skip recursion, a start-index loop, cascading or a bitmask all walk those 2ⁿ choices

Understand it

Start here

Subsets as a coding pattern

The task: given a list nums of distinct integers, return every subset, in any order. For [1, 2, 3] that is [], [1], [2], [3], [1, 2], [1, 3], [2, 3] and [1, 2, 3]. The maths of why there are 2n2^n of them is covered in Subsets and the power set, and the choose, explore, unchoose rhythm in Backtracking. This page is about the code: four ways to write it, how they differ, and what changes when values repeat.

Quick recap before the patterns

  • 2ⁿ subsets

    Each element is either in or out: 2×2×⋯×2=2n2 \times 2 \times \cdots \times 2 = 2^n, the empty set and the full set included.

  • Choose, explore, unchoose

    Append, recurse, pop. Every recursive version below is this template with a different loop.

  • Save a copy

    result.append(path[:]), never path itself, or every answer ends up as the same empty list.

The five patterns on this page

PatternIdeaWhere the answers are
Take or skipTwo recursive calls per elementLeaves of a full binary tree
Start-index loopLoop over later elements onlyEvery node of the tree
Iterative cascadingCopy every subset, add the next elementThe list doubles each round
Bitmask enumerationCount 0 to 2n−12^n - 1, read the bitsOne integer per subset
Subsets IISort, skip a repeat at the same levelEach distinct subset once

Pattern 1

Take or skip: one decision per element

The most literal version: walk the list by index, and at index i make two recursive calls, one with nums[i] taken and one without it. When i reaches the end every element has been decided, so the path is a complete subset. This is the shape House robber and knapsack use too.

The take-or-skip tree for [1, 2, 3]

Left edges take, right edges skip; the last level does the same for 3. Only the 8 green leaves are answers, and they come out in the order shown, full set first, empty set last.
Python
def subsets(nums):    result, path = [], []    def dfs(i):        if i == len(nums):            result.append(path[:])      # every element decided: a leaf            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 resultprint(subsets([1, 2, 3]))# [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
Take, recurse, pop, recurse. The pop is what turns the take branch into the skip branch.
Edit and run it in your browser

How many calls

T(n)=2 T(n−1)+O(1)  ⇒  1+2+4+⋯+2n=2n+1−1 callsT(n) = 2\,T(n-1) + O(1) \;\Rightarrow\; 1 + 2 + 4 + \cdots + 2^{n} = 2^{n+1} - 1 \text{ calls}
Each call makes two more until depth nn. For n=3n = 3 that is 15 calls for 8 answers: about twice as many calls as answers, which is still O(2n)O(2^n).

Pattern 2

Start index: every node is an answer

The version most solutions use: each call saves the current path straight away, then loops over the elements after the last one chosen. Because the loop never looks back, [2, 1] is never built as a copy of [1, 2]. Every node of this tree is a subset, so there are no wasted calls.

The start-index tree for [1, 2, 3]

8 nodes, 8 subsets, 8 calls. A node with start 3 has an empty loop, so it is a leaf. Visiting order gives lexicographic output: [], [1], [1,2], [1,2,3], [1,3], [2], [2,3], [3].
Python
def subsets(nums):    result, path = [], []    def backtrack(start):        result.append(path[:])          # 1. every node is a subset: save a copy        for i in range(start, len(nums)):   # 2. only elements after the last choice            path.append(nums[i])        # 3. choose            backtrack(i + 1)            # 4. explore with a later start            path.pop()                  # 5. unchoose    backtrack(0)    return resultprint(subsets([1, 2, 3]))# [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
The template to memorise. Five lines inside the helper: save, loop from start, choose, explore, unchoose.
Edit and run it in your browser

Side by side

Two trees, same answers

Take or skipStart index
Branches per callExactly 2n−startn - \text{start} (0 to nn)
Where answers areLeaves onlyEvery node
Calls for n=3n = 3158
Output orderFull set first, ∅\varnothing lastLexicographic
Grows intoKnapsack, target sum, take-or-skip DPCombinations, combination sum, partitions
Both are O(n⋅2n)O(n \cdot 2^n). Pick take-or-skip when each element carries its own decision (and maybe a cost), start-index when you are choosing a group.

Pattern 3

Iterative cascading: double the list

One round per element
  1. 1Startresult = [[]]
  2. 2Take xthe next element
  3. 3Copy alls + [x] for each s
  4. 4Appendthe list doubles
Repeat: back to Start

After element 1 the list is ∅, [1]; after 2 it is ∅, [1], [2], [1, 2]; after 3 it holds all 8.

Python
def subsets(nums):    result = [[]]    for x in nums:        result += [s + [x] for s in result]   # copy every subset, add x    return resultprint(subsets([1, 2, 3]))# [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
No recursion, no path, no pop. The comprehension is built from the old list before += extends it.
Edit and run it in your browser

Work done

1+2+4+⋯+2n−1⏟subsets copied=2n−1,each copy≤n  ⇒  O(n⋅2n)\underbrace{1 + 2 + 4 + \cdots + 2^{n-1}}_{\text{subsets copied}} = 2^{n} - 1, \qquad \text{each copy} \le n \;\Rightarrow\; O(n \cdot 2^{n})
Round kk copies the 2k−12^{k-1} subsets that exist so far. Position mm of the final list holds exactly the subset whose bitmask is mm, so this and the bitmask loop give the same order.

Pattern 4

Bitmask enumeration: a number is a subset

maskbinary (bit 2 1 0)subset of [1, 2, 3]
0000∅\varnothing
1001[1]
2010[2]
3011[1, 2]
4100[3]
5101[1, 3]
6110[2, 3]
7111[1, 2, 3]
Bit ii (counting from the right, from 0) stands for nums[i]. Counting from 0 to 2n−12^n - 1 visits every subset exactly once.
Python
def subsets(nums):    n = len(nums)    result = []    for mask in range(1 << n):          # 0 .. 2**n - 1        subset = [nums[i] for i in range(n) if mask >> i & 1]        result.append(subset)    return resultprint(subsets([1, 2, 3]))# [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]print(bin(5), subsets([1, 2, 3])[5])   # 0b101 [1, 3]
Two loops: one over masks, one over bits. Each mask costs n checks.
Edit and run it in your browser

Bit operations on a subset mask

OperationCodeResult
Is element ii in?mask >> i & 1 or mask & (1 << i)non-zero if included
Add element iimask | (1 << i)bit ii set
Remove element iimask & ~(1 << i)bit ii cleared
Toggle element iimask ^ (1 << i)bit ii flipped
Size of the subsetmask.bit_count() (Python 3.10+)number of 1 bits
Every subsetfor mask in range(1 << n)0 to 2n−12^n - 1
Union is a | b and intersection is a & b, one instruction each. That is why bitmask DP (travelling salesman, assignment) stores sets as integers.

Subsets II

Duplicates: sort, then skip at the same level

Now nums may repeat values, and the answer must not repeat subsets. On [1, 2, 2] the plain start-index code builds [1, 2] twice (once with each 2) and [2] twice. The fix has two parts: sort so equal values are neighbours, and in the loop skip nums[i] when i > start and nums[i] == nums[i - 1].

Start-index tree for sorted [1, 2, 2]

The dashed branches would rebuild what the first 2 already built at the same level. One level deeper, the second 2 may still follow the first, so [1, 2, 2] and [2, 2] survive. Result: 6 subsets.
Python
def subsets_with_dup(nums):    nums = sorted(nums)                 # equal values side by side    result, path = [], []    def backtrack(start):        result.append(path[:])        for i in range(start, len(nums)):            if i > start and nums[i] == nums[i - 1]:                continue                # this value was already tried at this level            path.append(nums[i])            backtrack(i + 1)            path.pop()    backtrack(0)    return resultprint(subsets_with_dup([1, 2, 2]))# [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
One extra line compared with plain subsets, plus the sort.
Edit and run it in your browser

How many distinct subsets

#distinct subsets=∏v(cv+1),[1,2,2]:  (1+1)(2+1)=6\#\text{distinct subsets} = \prod_{v} \big(c_v + 1\big), \qquad [1, 2, 2]:\; (1 + 1)(2 + 1) = 6
A distinct subset only decides how many copies of each value vv to take: 0, 1, ..., cvc_v. With all values distinct every cv=1c_v = 1 and the product is 2n2^n again.

Subsets II, version 2

Duplicates in the take-or-skip shape

The take-or-skip recursion handles duplicates differently: taking works as before, but skipping a value means skipping every copy of it at once. Otherwise skip-first-2-take-second-2 and take-first-2-skip-second-2 both give [2].

One call of dfs(i) with duplicates

Taking one copy can be followed by taking the next copy deeper down, so every count from 0 to c is still reachable exactly once.
Python
def subsets_with_dup(nums):    nums = sorted(nums)    result, path = [], []    def dfs(i):        if i == len(nums):            result.append(path[:])            return        path.append(nums[i])            # take this copy        dfs(i + 1)        path.pop()        j = i        while j < len(nums) and nums[j] == nums[i]:            j += 1                      # skip every copy of this value        dfs(j)    dfs(0)    return resultprint(subsets_with_dup([2, 1, 2]))# [[1, 2, 2], [1, 2], [1], [2, 2], [2], []]
Same 6 subsets as the start-index version, in take-first order.
Edit and run it in your browser

Variations

From subsets to combinations and sums

ProblemWhat changes in the template
Subsets (LeetCode 78)Nothing: save every node
Subsets II (90)Sort, skip nums[i] == nums[i - 1] when i > start
Combinations of size kk (77)Save only when len(path) == k, then return
Combination Sum (39)Recurse with i, not i + 1 (reuse allowed); break when too big
Combination Sum II (40)Sort, skip repeats at a level, recurse with i + 1
Subsets that sum to a targetCarry the running total; prune when it overshoots (sorted input)
Partition Equal Subset Sum (416)Enumeration is 2n2^n; memoise on (index, total) and it becomes DP
Partition to K Equal Sum Subsets (698)Bitmask of used elements as the DP state
"Find all subsets that sum to X" is a common interview question at large tech companies: subset generation plus a constraint check and pruning.
Python
def combine(n, k):    result, path = [], []    def backtrack(start):        if len(path) == k:            result.append(path[:])            return        need = k - len(path)        for x in range(start, n - need + 2):   # leave room for the rest            path.append(x)            backtrack(x + 1)            path.pop()    backtrack(1)    return resultprint(combine(4, 2))   # [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
Combinations of size k: the start-index loop, saving only at depth k, with a bound that stops the loop when too few numbers are left.
Edit and run it in your browser

Combinations get their own page next: Combinations. When a subset question asks for a count or a best value rather than the list, the same states repeat and dynamic programming takes over.

Complexity

Why O(n · 2ⁿ) is the floor

Total size of the output

∑k=0nk(nk)=n⋅2 n−1(n=3:  0+3+6+3=12=3⋅4)\sum_{k=0}^{n} k \binom{n}{k} = n \cdot 2^{\,n-1} \qquad (n = 3:\; 0 + 3 + 6 + 3 = 12 = 3 \cdot 4)
The average subset has n/2n/2 elements, so just writing every answer down takes Θ(n⋅2n)\Theta(n \cdot 2^n). No method can beat that; the four patterns all reach it.
MethodTimeExtra spaceOutput order for [1, 2, 3]
Take or skipO(n⋅2n)O(n \cdot 2^n)O(n)O(n) path and stack[1,2,3], [1,2], [1,3], [1], ..., []
Start indexO(n⋅2n)O(n \cdot 2^n)O(n)O(n) path and stack[], [1], [1,2], [1,2,3], [1,3], ...
CascadingO(n⋅2n)O(n \cdot 2^n)none beyond the output[], [1], [2], [1,2], [3], ...
BitmaskO(n⋅2n)O(n \cdot 2^n)O(n)O(n) for one subsetsame as cascading
Storing every answer needs O(n⋅2n)O(n \cdot 2^n) memory whichever method you use. A generator (yield) avoids that if the caller processes one subset at a time.

How big n can be

n2n2^n subsetsVerdict
532instant
101,024instant
1532,768fast
201,048,576about a million: the usual limit
2533,554,432too slow in Python
301,073,741,824about a billion: never
A constraint like n≤15n \le 15 or n≤20n \le 20 is a strong hint that the intended solution enumerates subsets or uses bitmask DP.

Choosing

Which pattern to write

Pick a pattern

All five give the right answer for distinct values; the choice is about what the problem adds on top: duplicates, pruning, storage or order.

Enumerate subsets when

  • The problem asks for all subsets, groups or selections.
  • nn is small, around 20 or less.
  • Each choice must be checked against a constraint as you go (pruning).
  • You need sets as DP states: bitmask over at most about 20 items.

Look for something else when

  • Only a count is wanted: there is often a formula or DP.
  • Only the best subset is wanted and states repeat: knapsack-style DP.
  • nn is in the hundreds or thousands: 2n2^n is out of reach.
  • Duplicates are removed afterwards with a set of tuples: correct but wasteful.

Recap

Key takeaways

Key points

  • A set of n elements has 2ⁿ subsets; listing them costs O(n · 2ⁿ), and that is the best possible.
  • Take or skip: two calls per element, answers only at the 2ⁿ leaves, 2ⁿ⁺¹ - 1 calls.
  • Start index: save at every node, loop from start, recurse with i + 1; 2ⁿ calls, lexicographic order.
  • Cascading: result += [s + [x] for s in result], doubling 1 → 2 → 4 → 8.
  • Bitmask: for mask in range(1 << n), take nums[i] when mask >> i & 1.
  • Always save a copy (path[:]) and pop after every recursive call.
  • Subsets II: sort, then skip nums[i] when i > start and nums[i] == nums[i - 1].
  • The empty set is always an answer: the root call, the all-skip leaf, mask 0.

Sources