AlgoViz

Subsets (power set)

easy 15 min

The power set of a set is the set of all its subsets.

Video lesson · Chapter 1 of 6

Three props, eight kits

0:00 / 4:47

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.

Step 1 of 3

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 SS is any selection of its items, in any number from none to all. The power set P(S)P(S) collects every possible subset. For S={a,b,c}S = \{a, b, c\} it holds eight sets: ∅\varnothing, {a}\{a\}, {b}\{b\}, {c}\{c\}, {a,b}\{a, b\}, {a,c}\{a, c\}, {b,c}\{b, c\} and {a,b,c}\{a, b, c\}. Order inside a subset does not matter, so {a,b}\{a, b\} and {b,a}\{b, a\} are the same subset.

The definition

P(S)={ T:T⊆S }∣P(S)∣=2∣S∣=2nP(S) = \{\, T : T \subseteq S \,\} \qquad |P(S)| = 2^{|S|} = 2^n
The power set is the set of all TT that are subsets of SS. A set with nn items has exactly 2n2^n subsets, which is where the name power set comes from.
  • Empty set ∅\varnothing

    Choose nothing. It is a subset of every set, and it always counts.

  • Proper subsets

    Everything between empty and full: here {a}\{a\}, {a,c}\{a, c\} and the rest.

  • The full set SS

    Choose everything. SS 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

2×2×⋯×2⏟n items=2ne.g.{a,b,c}:2×2×2=8\underbrace{2 \times 2 \times \cdots \times 2}_{n \text{ items}} = 2^n \qquad\text{e.g.}\qquad \{a, b, c\}: 2 \times 2 \times 2 = 8
Different decision lists always give different subsets, and every subset comes from exactly one decision list, so the count is exact.

One decision per item

Each new item doubles the number of ways to finish.
nnSet2n2^n subsets
0∅\varnothing1 (just ∅\varnothing)
1{a}\{a\}2
2{a,b}\{a, b\}4
3{a,b,c}\{a, b, c\}8
4{a,b,c,d}\{a, b, c, d\}16
Even the empty set has one subset: itself.

Mental model

The light switch method

Reading switches as a subset
  1. 1c switch: onbit 2 = 1
  2. 2b switch: offbit 1 = 0
  3. 3a switch: onbit 0 = 1
  4. 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 kkSubsets of {a,b,c}\{a, b, c\}Count (3k)\binom{3}{k}
0∅\varnothing1
1{a},{b},{c}\{a\}, \{b\}, \{c\}3
2{a,b},{a,c},{b,c}\{a, b\}, \{a, c\}, \{b, c\}3
3{a,b,c}\{a, b, c\}1
1+3+3+1=81 + 3 + 3 + 1 = 8. In general ∑k=0n(nk)=2n\sum_{k=0}^{n} \binom{n}{k} = 2^n: counting subsets by size is a row of Pascal's triangle.

Key CS concept

A number is a subset: bitmasks

Give item ii the bit worth 2i2^i: 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 00 to 2n−12^n - 1 is a different mask, so counting from 0 to 7 visits all eight subsets of {a,b,c}\{a, b, c\}.

DecimalBinaryc bit (222^2)b bit (212^1)a bit (202^0)Subset
0000000∅\varnothing
1001001{a}\{a\}
2010010{b}\{b\}
3011011{a,b}\{a, b\}
4100100{c}\{c\}
5101101{a,c}\{a, c\}
6110110{b,c}\{b, c\}
7111111{a,b,c}\{a, b, c\}
Bit 0 is the rightmost bit. Binary 101 has bits 0 and 2 on, so it means {a,c}\{a, c\}.

Is item i in the subset?

mask  &  (1≪i)≠0  ⟺  item i∈subset5 & 4=4≠0⇒c∈{a,c}\texttt{mask} \;\&\; (1 \ll i) \neq 0 \iff \text{item } i \in \text{subset} \qquad 5 \,\&\, 4 = 4 \neq 0 \Rightarrow c \in \{a, c\}
1 << i is a mask with only bit ii on. ANDing it with the mask keeps that one bit, so the test is a single O(1) operation.

Bitmask operations cheat sheet

GoalPythonResult
Is item ii in?mask & (1 << i)non-zero if included
Add item iimask | (1 << i)bit ii set
Remove item iimask & ~(1 << i)bit ii cleared
Toggle item iimask ^ (1 << i)bit ii flipped
Size of the subsetbin(mask).count("1")number of 1 bits (mask.bit_count() in Python 3.10+)
Every subsetfor mask in range(1 << n)0 to 2n−12^n - 1
In C++ the size is __builtin_popcount(mask); in Java Integer.bitCount(mask).

Method 1

Bitmask enumeration

The bitmask loop

Outer loop: one pass per subset. Inner loop: one bit test per item, so n⋅2nn \cdot 2^n tests in total.
Python
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']]
Count from 0 to 2^n - 1 and read each mask's bits.
Edit and run it in your browser

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 nn 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 2642^{64} masks is never practical anyway).

Method 2

Backtracking: the take-or-skip tree

Recursion makes the switch idea literal. dfs(i) decides item ii: 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 nn with 2n2^n leaves.

The include/exclude tree for {a, b, c}

Each level decides one item. The eight leaves on the bottom row are the eight subsets.
Python
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'], []]
Choose, explore, unchoose, explore again.
Edit and run it in your browser

Size of the tree

1+2+4+⋯+2n=2n+1−1 calls2n leavesdepth n1 + 2 + 4 + \cdots + 2^n = 2^{n+1} - 1 \text{ calls} \qquad 2^n \text{ leaves} \qquad \text{depth } n
For {a,b,c}\{a, b, c\}: 15 calls and 8 leaves. Only nn calls are on the stack at once, so the extra space is O(n) beyond the output.

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 2n2^n calls.

Python
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]]
The backtracking template behind subsets, combinations and combination sum.
Edit and run it in your browser
The three moves
  1. 1Choosepath.append(x)
  2. 2Explorebacktrack(i + 1)
  3. 3Unchoosepath.pop()
Repeat: back to Choose

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 nn.
  • 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 xx, copy every subset you already have and add xx to the copy. Old subsets are the ones without xx, copies are the ones with xx, so together they are all subsets of the items seen so far.

Each item doubles the list

The final order matches the bitmask order: position 5 holds ac, and 5 is 101 in binary.

The doubling

∣R0∣=1,∣Rk∣=2 ∣Rk−1∣⇒∣Rn∣=2n1→2→4→8|R_0| = 1, \quad |R_k| = 2\,|R_{k-1}| \quad\Rightarrow\quad |R_n| = 2^n \qquad 1 \to 2 \to 4 \to 8
RkR_k is the list after kk items. Each round keeps every old subset and adds one copy of each.
Python
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']]
The one-line form builds the new half before adding it, so it is safe.
Edit and run it in your browser

Complexity

Cost: O(n · 2ⁿ) and why

Total size of the output

∑k=0nk(nk)=n⋅2 n−1⇒time and space O(n⋅2n)\sum_{k=0}^{n} k \binom{n}{k} = n \cdot 2^{\,n-1} \qquad\Rightarrow\qquad \text{time and space } O(n \cdot 2^n)
There are 2n2^n subsets and their average size is n/2n/2, so writing them all out touches n⋅2n−1n \cdot 2^{n-1} elements. No method can be faster than its own output.

How far you can go

nn2n2^n subsetsPractical?
532Instant
101,024Instant, about a thousand
1532,768Fast, about 32 thousand
201,048,576The usual limit, about a million
2533,554,432Too slow to list, about 33 million
301,073,741,824Hopeless, about a billion
If the constraints say n≤20n \le 20, the problem is inviting you to try every subset.

The three methods side by side

MethodTimeExtra spaceOrderBest for
BitmaskO(n⋅2n)O(n \cdot 2^n)O(1)O(1)Binary countSubsets as integers, bitmask DP
BacktrackingO(n⋅2n)O(n \cdot 2^n)O(n)O(n) stackDepth firstConstraints and pruning
Iterative doublingO(n⋅2n)O(n \cdot 2^n)O(1)O(1)Binary countShort code, no recursion
Extra space leaves out the O(n⋅2n)O(n \cdot 2^n) output itself, which every method needs if it returns all subsets.

Choosing

Which method to reach for

Pick a method

All three list the same 2n2^n subsets; the choice is about what else the problem needs.
Python
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]]
Subsets with duplicate values, using the same template.
Edit and run it in your browser

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: kk flags give 2k2^k 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

ProblemIdeaLevel
Subsets (LeetCode 78)Return all subsets of distinct numbers: any of the three methodsMedium
Subsets II (LeetCode 90)Input has duplicates: sort, skip equal neighboursMedium
Combination Sum (LeetCode 39)Subsets that hit a target, items reusable: backtrack, recurse on iMedium
Combination Sum II (LeetCode 40)No reuse, duplicates in input: recurse on i + 1, skip equal neighboursMedium
Partition Equal Subset Sum (LeetCode 416)Is there a subset summing to half the total? Subset-sum DPMedium
Partition to K Equal Sum Subsets (LeetCode 698)Bitmask DP over which items are usedHard
Many problems reduce to: generate subsets, then check a constraint, then prune.

Recap

Key takeaways

Key points

  • The power set holds every subset, including ∅\varnothing and the full set; nn items give exactly 2n2^n subsets.
  • Why 2n2^n: each item is independently in or out, 2×2×⋯×22 \times 2 \times \cdots \times 2.
  • Bitmask: each integer from 0 to 2n−12^n - 1 is one subset; mask & (1 << i) tests item ii 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, 1→2→4→81 \to 2 \to 4 \to 8.
  • All three cost O(n⋅2n)O(n \cdot 2^n) because the output itself has n⋅2n−1n \cdot 2^{n-1} elements.
  • Use it when nn is about 20 or less; with duplicates, sort and skip equal neighbours.

Sources