Subsets (power set)
easy 15 minThe power set of a set is the set of all its subsets.
Video lesson · Chapter 1 of 6
Three props, eight kits
Subsets and the power set
1:26Reel
Read caption
Nox enumerates all eight subsets of three treasures and watches one path form a particular bag. Take or skip. Every new item doubles the possibilities.
How it works
Step through the idea, or press Play.
Every item is in or out. A subset is one in-or-out decision per item, so n items give 2 × 2 × ... × 2 = 2^n subsets
Understand it
Start here
What the power set is
A subset of a set is any selection of its items, in any number from none to all. The power set collects every possible subset. For it holds eight sets: , , , , , , and . Order inside a subset does not matter, so and are the same subset.
The definition
Empty set
Choose nothing. It is a subset of every set, and it always counts.
Proper subsets
Everything between empty and full: here , and the rest.
The full set
Choose everything. is a subset of itself, so it counts too.
The counting argument
Why there are exactly 2ⁿ subsets
Build a subset by walking through the items and making one decision per item: take it or skip it. The decisions are independent, so the number of different outcomes is the product of the choices at each item.
Two choices per item
One decision per item
| Set | subsets | |
|---|---|---|
| 0 | 1 (just ) | |
| 1 | 2 | |
| 2 | 4 | |
| 3 | 8 | |
| 4 | 16 |
Mental model
The light switch method
- 1c switch: onbit 2 = 1
- 2b switch: offbit 1 = 0
- 3a switch: onbit 0 = 1
- 4101 in binarythe number 5 = {a, c}
Every switch setting is a number from 0 to $2^n - 1$, and every such number is a switch setting.
How subsets grow by size
| Size | Subsets of | Count |
|---|---|---|
| 0 | 1 | |
| 1 | 3 | |
| 2 | 3 | |
| 3 | 1 |
Key CS concept
A number is a subset: bitmasks
Give item the bit worth : a is bit 0, b bit 1, c bit 2. A bitmask is an integer whose 1 bits mark the items that are in. Every integer from to is a different mask, so counting from 0 to 7 visits all eight subsets of .
| Decimal | Binary | c bit () | b bit () | a bit () | Subset |
|---|---|---|---|---|---|
| 0 | 000 | 0 | 0 | 0 | |
| 1 | 001 | 0 | 0 | 1 | |
| 2 | 010 | 0 | 1 | 0 | |
| 3 | 011 | 0 | 1 | 1 | |
| 4 | 100 | 1 | 0 | 0 | |
| 5 | 101 | 1 | 0 | 1 | |
| 6 | 110 | 1 | 1 | 0 | |
| 7 | 111 | 1 | 1 | 1 |
101 has bits 0 and 2 on, so it means .Is item i in the subset?
1 << i is a mask with only bit on. ANDing it with the mask keeps that one bit, so the test is a single O(1) operation.Bitmask operations cheat sheet
| Goal | Python | Result |
|---|---|---|
| Is item in? | mask & (1 << i) | non-zero if included |
| Add item | mask | (1 << i) | bit set |
| Remove item | mask & ~(1 << i) | bit cleared |
| Toggle item | mask ^ (1 << i) | bit flipped |
| Size of the subset | bin(mask).count("1") | number of 1 bits (mask.bit_count() in Python 3.10+) |
| Every subset | for mask in range(1 << n) | 0 to |
__builtin_popcount(mask); in Java Integer.bitCount(mask).Method 1
Bitmask enumeration
The bitmask loop
def subsets_bitmask(items): n = len(items) result = [] for mask in range(1 << n): # 1 << n == 2**n subset = [items[i] for i in range(n) if mask & (1 << i)] result.append(subset) return resultprint(subsets_bitmask(["a", "b", "c"]))# [[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]Strengths
- Simple loops, no recursion stack.
- Natural order: the subsets come out in binary counting order.
- A subset is a plain integer, perfect as a dictionary key or a DP state.
Limits
- Tests all bits for every mask, even when most are off.
- Hard to prune: every mask is visited, wanted or not.
- Fits in a machine word only up to about 63 items (Python ints grow, but masks is never practical anyway).
Method 2
Backtracking: the take-or-skip tree
Recursion makes the switch idea literal. dfs(i) decides item : first take it (append, recurse, then pop to undo), then skip it (recurse without it). When every item is decided, the path is one subset. The calls form a binary tree of depth with leaves.
The include/exclude tree for {a, b, c}
def subsets_backtrack(items): result, path = [], [] def dfs(i): if i == len(items): # every item decided result.append(path[:]) # save a COPY return path.append(items[i]) # choose: take items[i] dfs(i + 1) # explore with it path.pop() # unchoose dfs(i + 1) # explore without it dfs(0) return resultprint(subsets_backtrack(["a", "b", "c"]))# [['a', 'b', 'c'], ['a', 'b'], ['a', 'c'], ['a'], ['b', 'c'], ['b'], ['c'], []]Size of the tree
Template to memorise
Choose, explore, unchoose
The most common interview form drops the explicit skip call. Each call saves the current path on entry, then tries adding each remaining item, starting after the last one used. Every node of this tree is a subset, so there are exactly calls.
def subsets(nums): result, path = [], [] def backtrack(start): result.append(path[:]) # 1. record the current subset (copy!) for i in range(start, len(nums)): path.append(nums[i]) # 2. CHOOSE: include nums[i] backtrack(i + 1) # 3. EXPLORE: only later items path.pop() # 4. UNCHOOSE: undo, try the next one backtrack(0) return resultprint(subsets([1, 2, 3]))# [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]- 1Choosepath.append(x)
- 2Explorebacktrack(i + 1)
- 3Unchoosepath.pop()
Starting the loop at start, not 0, is what stops $\{1, 2\}$ and $\{2, 1\}$ from both appearing.
Strengths
- Easy to add constraints: stop when a sum is too big, or the size is reached.
- Natural for pruning whole branches.
- The same template solves combinations, combination sum and Subsets II.
Costs
- Recursion stack overhead, up to depth .
- Easy to forget the copy or the pop.
- Output order is depth-first, not binary counting order.
Method 3
Iterative doubling
Start with [[]], the list holding only the empty set. For each item , copy every subset you already have and add to the copy. Old subsets are the ones without , copies are the ones with , so together they are all subsets of the items seen so far.
Each item doubles the list
The doubling
def subsets_iterative(items): result = [[]] # start with the empty set for x in items: result += [s + [x] for s in result] # copy each subset, add x return resultprint(subsets_iterative(["a", "b", "c"]))# [[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]Complexity
Cost: O(n · 2ⁿ) and why
Total size of the output
How far you can go
| subsets | Practical? | |
|---|---|---|
| 5 | 32 | Instant |
| 10 | 1,024 | Instant, about a thousand |
| 15 | 32,768 | Fast, about 32 thousand |
| 20 | 1,048,576 | The usual limit, about a million |
| 25 | 33,554,432 | Too slow to list, about 33 million |
| 30 | 1,073,741,824 | Hopeless, about a billion |
The three methods side by side
| Method | Time | Extra space | Order | Best for |
|---|---|---|---|---|
| Bitmask | Binary count | Subsets as integers, bitmask DP | ||
| Backtracking | stack | Depth first | Constraints and pruning | |
| Iterative doubling | Binary count | Short code, no recursion |
Choosing
Which method to reach for
Pick a method
def subsets_with_dup(nums): nums = sorted(nums) 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 # same value already tried at this depth 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]]Why it matters
Where subsets show up
Bitmask dynamic programming
A mask of visited cities or used workers becomes the DP state: travelling salesman, set cover, assignment problems.
Combinatorial optimisation
Try every choice of items to find the best: knapsack on small inputs, partition problems, subset sum.
Software testing
Feature flag and configuration combinations: flags give setups to cover or sample.
Permissions
A set of permissions is a subset, stored as bits: Unix read, write and execute are the mask
rwx.
Must-know interview problems
| Problem | Idea | Level |
|---|---|---|
| Subsets (LeetCode 78) | Return all subsets of distinct numbers: any of the three methods | Medium |
| Subsets II (LeetCode 90) | Input has duplicates: sort, skip equal neighbours | Medium |
| Combination Sum (LeetCode 39) | Subsets that hit a target, items reusable: backtrack, recurse on i | Medium |
| Combination Sum II (LeetCode 40) | No reuse, duplicates in input: recurse on i + 1, skip equal neighbours | Medium |
| Partition Equal Subset Sum (LeetCode 416) | Is there a subset summing to half the total? Subset-sum DP | Medium |
| Partition to K Equal Sum Subsets (LeetCode 698) | Bitmask DP over which items are used | Hard |
Recap
Key takeaways
Key points
- The power set holds every subset, including and the full set; items give exactly subsets.
- Why : each item is independently in or out, .
- Bitmask: each integer from 0 to is one subset;
mask & (1 << i)tests item in O(1). - Backtracking: choose, explore, unchoose, and always save a copy of the path.
- Iterative doubling: start from
[[]]and copy every subset with the new item added, . - All three cost because the output itself has elements.
- Use it when is about 20 or less; with duplicates, sort and skip equal neighbours.