AlgoViz

Subsets (power set)

easy 15 min

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

See it run

Count masks 0 to 7 to read off all 8 subsets of {a, b, c}, walk the include/exclude tree, double a list from 1 to 8, and watch 2^n leave n and n^2 behind.

Operations

Bitmask Method

Give each item one bit. Every number from $0$ to $2^n - 1$ is then a different on/off pattern, so counting through them lists every subset exactly once.

Step 1 of 12

Three items, eight masks

8421
1 << 310008 masks
last01117 = 2³ − 1

bit 0 = a, bit 1 = b, bit 2 = c

Our set is {a, b, c}, so n = 3. Give a bit 0, b bit 1 and c bit 2. 1 << 3 is 2^3 = 8, so the masks run from 0 to 7, and each one will name a subset.

Step 1: Three items, eight masks

def subsets_bitmask(items):    n = len(items)    result = []    for mask in range(1 << n):          # 0 .. 2**n - 1        subset = []        for i in range(n):            if mask & (1 << i):         # is bit i on?                subset.append(items[i])        result.append(subset)    return resultprint(subsets_bitmask(["a", "b", "c"]))# [[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
Time
O(n · 2^n)
Space
O(n · 2^n) output
masks for n items
2^n, from 0 to 2^n - 1
test one item
mask & (1 << i), O(1)

Test a bit with if mask & (1 << i): and never with == 1. The AND gives 2^i, not 1, for every bit except bit 0.

Common mistakes

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

  • Saving the path without copying it

    critical

    Lists are references. result.append(path) stores the same list object every time, so after the final pops every entry is the same empty list.

    Wrong
    def dfs(i):    if i == len(items):        result.append(path)       # [[], [], [], ...]        return
    Right
    def dfs(i):    if i == len(items):        result.append(path[:])    # or list(path)        return
  • Forgetting to pop after the recursive call

    critical

    Without the undo, the skip branch still carries the item you just took, and items pile up across branches. Every append needs a matching pop.

    Wrong
    path.append(items[i])dfs(i + 1)dfs(i + 1)                        # path still holds items[i]
    Right
    path.append(items[i])dfs(i + 1)path.pop()                        # undo the choicedfs(i + 1)
  • Looping from 0 instead of start

    major

    In the for-loop template each call must only add items after the last one. Starting at 0 builds orderings such as [b, a] as well as [a, b], and never stops adding.

    Wrong
    def dfs(start):    result.append(path[:])    for i in range(len(items)):   # revisits earlier items        ...
    Right
    def dfs(start):    result.append(path[:])    for i in range(start, len(items)):        path.append(items[i])        dfs(i + 1)        path.pop()
  • Testing a bit with == 1

    major

    mask & (1 << i) is 2^i when bit i is on, so it equals 1 only for bit 0. Test for non-zero instead.

    Wrong
    if mask & (1 << i) == 1:          # True only when i == 0    subset.append(items[i])
    Right
    if mask & (1 << i):               # any non-zero value means on    subset.append(items[i])# or: if (mask >> i) & 1:
  • Appending to the list you are looping over

    critical

    In the iterative build, a plain for loop over result also visits the subsets added during this round, so the loop never ends. Freeze the size first, or build the new half separately.

    Wrong
    for x in items:    for s in result:        result.append(s + [x])   # runs forever
    Right
    for x in items:    result += [s + [x] for s in result]   # new half built first, then added
  • Dropping the empty set

    minor

    The empty set is a subset of every set, and it is mask 0. Starting the count at 1 returns 2^n - 1 subsets and fails the count check.

    Wrong
    for mask in range(1, 1 << n):    # misses the empty set    ...
    Right
    for mask in range(1 << n):       # 0 .. 2**n - 1, all 2**n    ...

Interview tips

  • Spot it fast

    • "Return all subsets", "all combinations" or "every way to pick".
    • Each element is either chosen or not: a take-or-skip decision.
    • n is small, around 20 or less.
    • "Can the array be split so that...": try every subset as one side.
  • Numbers to know cold

    • n items have 2^n subsets: 8, 1,024, about a million at n = 20.
    • The include/exclude tree has 2^(n+1) - 1 calls and 2^n leaves.
    • Writing every subset out touches n · 2^(n-1) elements in total.
    • There are C(n, k) subsets of size k, and they sum to 2^n.
  • Say it in the interview

    • "Each element is in or out, so there are 2^n subsets and I can't beat O(n · 2^n) if I must output them."
    • "I'll backtrack: choose, explore, unchoose, and save a copy of the path."
    • Mention the bitmask version as an iterative alternative with no recursion.
    • With duplicates, sort first and skip equal neighbours at the same depth.
  • Traps

    • Forgetting path[:] gives a list of empty lists.
    • mask & (1 << i) == 1 only works for bit 0.
    • Duplicate input values produce duplicate subsets unless you skip them.
    • Beyond about n = 25, enumerating every subset is too slow.