Subsets
medium 22 minGenerating 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
Subsets in 75 seconds
1:26Reel
How it works
Step through the idea, or press Play.
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 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: , 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[:]), neverpathitself, or every answer ends up as the same empty list.
The five patterns on this page
| Pattern | Idea | Where the answers are |
|---|---|---|
| Take or skip | Two recursive calls per element | Leaves of a full binary tree |
| Start-index loop | Loop over later elements only | Every node of the tree |
| Iterative cascading | Copy every subset, add the next element | The list doubles each round |
| Bitmask enumeration | Count 0 to , read the bits | One integer per subset |
| Subsets II | Sort, skip a repeat at the same level | Each 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]
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], []]How many calls
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]
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]]Side by side
Two trees, same answers
| Take or skip | Start index | |
|---|---|---|
| Branches per call | Exactly 2 | (0 to ) |
| Where answers are | Leaves only | Every node |
| Calls for | 15 | 8 |
| Output order | Full set first, last | Lexicographic |
| Grows into | Knapsack, target sum, take-or-skip DP | Combinations, combination sum, partitions |
Pattern 3
Iterative cascading: double the list
- 1Startresult = [[]]
- 2Take xthe next element
- 3Copy alls + [x] for each s
- 4Appendthe list doubles
After element 1 the list is ∅, [1]; after 2 it is ∅, [1], [2], [1, 2]; after 3 it holds all 8.
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]]Work done
Pattern 4
Bitmask enumeration: a number is a subset
| mask | binary (bit 2 1 0) | subset of [1, 2, 3] |
|---|---|---|
| 0 | 000 | |
| 1 | 001 | [1] |
| 2 | 010 | [2] |
| 3 | 011 | [1, 2] |
| 4 | 100 | [3] |
| 5 | 101 | [1, 3] |
| 6 | 110 | [2, 3] |
| 7 | 111 | [1, 2, 3] |
nums[i]. Counting from 0 to visits every subset exactly once.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]Bit operations on a subset mask
| Operation | Code | Result |
|---|---|---|
| Is element in? | mask >> i & 1 or mask & (1 << i) | non-zero if included |
| Add element | mask | (1 << i) | bit set |
| Remove element | mask & ~(1 << i) | bit cleared |
| Toggle element | mask ^ (1 << i) | bit flipped |
| Size of the subset | mask.bit_count() (Python 3.10+) | number of 1 bits |
| Every subset | for mask in range(1 << n) | 0 to |
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]
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]]How many distinct subsets
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
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], []]Variations
From subsets to combinations and sums
| Problem | What 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 (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 target | Carry the running total; prune when it overshoots (sorted input) |
| Partition Equal Subset Sum (416) | Enumeration is ; memoise on (index, total) and it becomes DP |
| Partition to K Equal Sum Subsets (698) | Bitmask of used elements as the DP state |
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 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
| Method | Time | Extra space | Output order for [1, 2, 3] |
|---|---|---|---|
| Take or skip | path and stack | [1,2,3], [1,2], [1,3], [1], ..., [] | |
| Start index | path and stack | [], [1], [1,2], [1,2,3], [1,3], ... | |
| Cascading | none beyond the output | [], [1], [2], [1,2], [3], ... | |
| Bitmask | for one subset | same as cascading |
yield) avoids that if the caller processes one subset at a time.How big n can be
| n | subsets | Verdict |
|---|---|---|
| 5 | 32 | instant |
| 10 | 1,024 | instant |
| 15 | 32,768 | fast |
| 20 | 1,048,576 | about a million: the usual limit |
| 25 | 33,554,432 | too slow in Python |
| 30 | 1,073,741,824 | about a billion: never |
Choosing
Which pattern to write
Pick a pattern
Enumerate subsets when
- The problem asks for all subsets, groups or selections.
- 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.
- is in the hundreds or thousands: 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.