AlgoViz

O(2ⁿ) exponential space

easy 15 min

O(2ⁿ) space means the memory doubles every time one more item is added.

See it run

Watch memory double with every item: the power set stored mask by mask, the Held–Karp table of 16 × 4 slots, a subset-sum memo growing level by level, and what 2ⁿ entries cost in bytes.

Operations

Store the power set

Generate and keep every subset of {A, B, C}. Each mask from 0 to 7 picks one subset (bit i = item i), and every one of them is appended to a list that is never freed.

Step 1 of 10

Every subset is a 3-bit mask

421
C B A000mask 0 = { }
C B A101mask 5 = {A,C}
C B A111mask 7 = {A,B,C}

3 items → 2³ = 8 masks → 8 stored lists

Each item is in (1) or out (0), so three items give 2 \times 2 \times 2 = 2^3 = 8 masks, the numbers 0 to 7. Bit 0 stands for A, bit 1 for B, bit 2 for C. The function keeps every subset it builds, so the space it needs is the size of the whole power set.

Step 1: Every subset is a 3-bit mask

def power_set(items):    n = len(items)    result = []    for mask in range(1 << n):          # 2^n masks: 0 .. 2^n - 1        subset = []        for i in range(n):            if mask & (1 << i):         # bit i set: take items[i]                subset.append(items[i])        result.append(subset)           # kept: memory only grows    return result                       # 2^n lists, n * 2^(n-1) items
Time
O(n · 2ⁿ)
Space
O(n · 2ⁿ) output
n = 20
1,048,576 subsets stored
count only
O(1) space: 2 ** n

If the caller only needs to look at each subset once, yield it instead of storing it: the time stays O(n · 2ⁿ) but the memory drops to O(n).

Common mistakes

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

  • Storing every subset when you only need to look at each one

    critical

    Building the whole power set keeps 2ⁿ lists alive at once. If each subset is only checked or counted, a generator produces the same subsets with O(n) memory.

    Wrong
    subsets = power_set(items)          # 2^n lists in memorybest = max(subsets, key=score)
    Right
    def each_subset(items):    n = len(items)    for mask in range(1 << n):        yield [items[i] for i in range(n) if mask >> i & 1]best = max(each_subset(items), key=score)   # O(n) memory
  • Allocating a 2ⁿ table without checking n

    critical

    [0] * (1 << n) is instant to write and fatal at n = 40: about 8 TiB. Python list slots are 8-byte pointers, so even n = 30 needs about 8 GiB before storing a single value.

    Wrong
    dp = [0] * (1 << n)     # n = 40: about 8 TiB, MemoryError
    Right
    if n > 25:    raise ValueError("bitmask DP needs n <= 25; use pruning or meet in the middle")dp = [0] * (1 << n)
  • Keying the memo on the whole subset

    major

    A key like a tuple of chosen items is different for every path, so there are 2ⁿ keys and no hits. What matters for the future is only (index, sum), which has at most n · (target + 1) values.

    Wrong
    key = (i, tuple(chosen))    # 2^n distinct keys, never a hit
    Right
    key = (i, s)                # at most n * (target + 1) keys
  • Dropping the last-city column in Held–Karp

    major

    dp[mask] alone does not know where the path ends, so it cannot add the next distance correctly. The n columns are what make the answer right, and they are why the space is O(n · 2ⁿ), not O(2ⁿ).

    Wrong
    dp = [INF] * (1 << n)               # where are we standing?
    Right
    dp = [[INF] * n for _ in range(1 << n)]   # dp[mask][last]
  • Appending the working list instead of a copy

    major

    In backtracking, current is reused. Storing it directly keeps 2ⁿ references to one list, which is empty at the end. Each stored subset must be its own copy, and that copy is exactly the O(n · 2ⁿ) output memory.

    Wrong
    result.append(current)      # 2^n references to one list
    Right
    result.append(current[:])   # a real copy of this subset
  • Using lists of Python ints for a huge boolean table

    minor

    A Python list spends 8 bytes per slot on a pointer. For a yes or no per mask, a bytearray uses 1 byte per mask and a bitset 1 bit, so 2³⁰ masks need 1 GiB or 128 MiB instead of 8 GiB.

    Wrong
    seen = [False] * (1 << n)        # 8 bytes per mask
    Right
    seen = bytearray(1 << n)         # 1 byte per mask

Interview tips

  • How to say it

    • "This stores all 2ⁿ subsets, so the space is O(n · 2ⁿ) for the output."
    • "The bitmask DP table has 2ⁿ × n entries, one per (visited set, last city)."
    • "This is only practical for n up to about 20 to 25 because of the memory."
  • Spot it in code

    • An allocation of size `1 << n`, or `(1 << n) * n`.
    • A result list that every subset is appended to.
    • A memo whose key is a mask or a whole subset.
    • A problem that says "return all subsets" or "power set".
  • Memory tricks

    • Power Set Explosion: every element doubles the storage.
    • 2²⁰ entries × 8 bytes = 8 MiB; +10 to n is ×1,024 the memory.
    • Russian dolls: each level holds two smaller copies, so n levels hold 2ⁿ.
  • Warning signs

    • If n > 25 and your plan needs O(2ⁿ) memory, look for a polynomial DP, pruning or meet in the middle.
    • Exponential time does not force exponential space: plain backtracking uses O(n).
    • A memo can be far smaller than 2ⁿ when its key has few distinct values.