AlgoViz

O(2ⁿ) exponential space

easy 15 min

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

Video lesson · Chapter 1 of 6

One drawer for every subset

0:00 / 6:12

O(2ⁿ) exponential space

1:23Reel

Read caption

A sound engineer stores a one-flag test result for every configuration of her effects switches. One switch doubles the verdicts.

How it works

Step through the idea, or press Play.

Step 1 of 3

One slot per subset. Each item is in or out, so there are 2ⁿ subsets; storing all of them, or one entry for each, takes 2ⁿ slots

Understand it

Start here

What O(2ⁿ) space means

An algorithm uses O(2ⁿ) space when the memory it holds at one time doubles with each extra input element. The usual cause is storing something for every subset: the subsets themselves (the power set), or one DP entry per subset, written as a bit mask. Time can often be waited out; memory cannot. If the table does not fit, the program crashes.

  • 2ⁿ subsets, 2ⁿ entries

    Each item is in or out, so nn items have 2n2^n subsets. Store one thing per subset and you need 2n2^n slots.

  • +1 item, ×2 memory

    Going from nn to n+1n + 1 doubles the table, because 2n+1=2⋅2n2^{n+1} = 2 \cdot 2^n.

  • Safe up to about 20 to 25

    2202^{20} entries is 8 MiB. 2302^{30} is 8 GiB, more than most machines will give one program.

Doubling, written out

S(n+1)=2⋅S(n),S(0)=1  ⟹  S(n)=2nS(n + 1) = 2 \cdot S(n), \quad S(0) = 1 \;\Longrightarrow\; S(n) = 2^n
If every new item doubles the number of things kept, the count after nn items is 2n2^n: 2, 4, 8, 16, 32, 64, 128 for n=1n = 1 to 7.

The picture

Why 2ⁿ: the include or exclude tree

Include or exclude, for A and B

Each level decides one item. Two items give 22=42^2 = 4 leaves and every leaf is a different subset. Keeping all the leaves is what costs exponential memory.

Two choices per item

2×2×⋯×2⏟n items=2n{A,B,C}:  23=8 subsets\underbrace{2 \times 2 \times \cdots \times 2}_{n \text{ items}} = 2^n \qquad \{A, B, C\}: \; 2^3 = 8 \text{ subsets}
The choices are independent, so the counts multiply. The empty set and the full set are both included.

Scale

The memory danger zone

n2n2^n entriesAt 8 bytes eachPractical?
101,0248 KiBYes
1532,768256 KiBYes
201,048,5768 MiBYes
2533,554,432256 MiBBorderline
301,073,741,8248 GiBNo
40about 1.1 trillion8 TiBNo
8 bytes is one 64-bit number or one Python list slot. Python objects cost more, so real programs hit the wall even sooner.

Memory at n = 20, 30 and 40

220⋅8 B=223 B=8 MiB230⋅8 B=233 B=8 GiB240⋅8 B=243 B=8 TiB\begin{aligned} 2^{20} \cdot 8\ \text{B} &= 2^{23}\ \text{B} = 8\ \text{MiB} \\ 2^{30} \cdot 8\ \text{B} &= 2^{33}\ \text{B} = 8\ \text{GiB} \\ 2^{40} \cdot 8\ \text{B} &= 2^{43}\ \text{B} = 8\ \text{TiB} \end{aligned}
Each +10 to nn multiplies the bytes by 210=1,0242^{10} = 1{,}024: kilo to mega to giga to tera.

Example 1

Storing the power set

The stored list doubles with each item
  1. 1Start[ { } ]: 1 subset
  2. 2Add Acopy each, add A: 2 subsets
  3. 3Add Bcopy each, add B: 4 subsets
  4. 4Add Ccopy each, add C: 8 subsets

Every item makes a copy of everything stored so far, which is exactly doubling.

Python
def power_set_doubling(items):    result = [[]]                                   # start with the empty set    for x in items:        result += [s + [x] for s in result]         # every item doubles the list    return resultdef power_set_masks(items):    n = len(items)    return [[items[i] for i in range(n) if mask >> i & 1]   # bit i = items[i]            for mask in range(1 << n)]ps = power_set_doubling(["A", "B", "C"])print(len(ps), ps)                      # 8 [[], ['A'], ['B'], ['A', 'B'], ['C'], ...]print(power_set_masks(["A", "B", "C"]) == ps)   # True: same orderprint(sum(len(s) for s in ps))          # 12 = 3 * 2 ** 2 stored items
Two ways to build and keep every subset. Both hold 2ⁿ lists at the end.
Edit and run it in your browser

Output size: more than 2ⁿ

∑k=0nk(nk)=n⋅2n−1  ⟹  memory=O(n⋅2n)\sum_{k=0}^{n} k \binom{n}{k} = n \cdot 2^{n-1} \;\Longrightarrow\; \text{memory} = O(n \cdot 2^n)
There are 2n2^n lists, and each item sits in exactly half of them, so they hold n⋅2n−1n \cdot 2^{n-1} items in total: 12 for {A,B,C}\{A, B, C\}, about 10 million for n=20n = 20. Saying "O(2n)O(2^n) subsets" counts the lists; the precise memory is O(n⋅2n)O(n \cdot 2^n).

Example 2

Bitmask DP: one entry per subset

Bitmask DP stores an answer for every subset, using the subset's mask as an array index. With nn items the masks run from 0 to 2n−12^n - 1, so the table has 2n2^n entries before it holds any extra dimension.

A mask is a subset and an index

MaskBinary (C B A)SubsetMaskBinary (C B A)Subset
0000{ }4100{C}
1001{A}5101{A, C}
2010{B}6110{B, C}
3011{A, B}7111{A, B, C}
Bit ii is item ii. dp[5] is the answer for {A, C}; dp = [0] * (1 << n) reserves a slot for every subset.

Table size

∣dp∣=2n∣dp[mask][extra]∣=2n⋅k|\text{dp}| = 2^n \qquad |\text{dp}[\text{mask}][\text{extra}]| = 2^n \cdot k
Any extra index, such as the last city in a tour, multiplies the table. That is how Held–Karp ends up at n⋅2nn \cdot 2^n.

Example 3

Held–Karp: TSP with a dp[mask][city] table

States and time

2n⏟visited sets⋅n⏟last city=n⋅2n states,time=n⋅2n⋅O(n)=O(n2⋅2n)\underbrace{2^n}_{\text{visited sets}} \cdot \underbrace{n}_{\text{last city}} = n \cdot 2^n \text{ states}, \qquad \text{time} = n \cdot 2^n \cdot O(n) = O(n^2 \cdot 2^n)
dp[mask][last] is the cheapest path from A that visits exactly the cities in mask and ends at last. Each state looks back at up to nn earlier cities. For 4 cities the table has 16×4=6416 \times 4 = 64 slots.

How the table is filled

Smaller masks come first, so every prev row is ready when it is needed. Every row must stay in memory until the end.
Python
def held_karp(d):    n = len(d)    INF = float("inf")    dp = [[INF] * n for _ in range(1 << n)]   # 2^n rows x n columns    dp[1][0] = 0                              # only A visited, standing at A    for mask in range(1 << n):        if not mask & 1:            continue                          # every path starts at A        for last in range(1, n):            if not mask & (1 << last):                continue            prev = mask ^ (1 << last)            dp[mask][last] = min(dp[prev][k] + d[k][last]                                 for k in range(n) if prev & (1 << k))    full = (1 << n) - 1    used = sum(v < INF for row in dp for v in row)    print("slots:", len(dp) * n, "reachable:", used)   # slots: 64 reachable: 13    return min(dp[full][k] + d[k][0] for k in range(1, n))d = [[0, 10, 15, 20],     [10, 0, 35, 25],     [15, 35, 0, 30],     [20, 25, 30, 0]]print(held_karp(d))   # 80: A -> B -> D -> C -> A
Four cities, A-B 10, A-C 15, A-D 20, B-C 35, B-D 25, C-D 30. The visualizer fills this exact table.
Edit and run it in your browser

Held–Karp memory at n = 20, 30 and 40

20⋅220⋅8 B≈160 MiB30⋅230⋅8 B≈240 GiB40⋅240⋅8 B≈320 TiB\begin{aligned} 20 \cdot 2^{20} \cdot 8\ \text{B} &\approx 160\ \text{MiB} \\ 30 \cdot 2^{30} \cdot 8\ \text{B} &\approx 240\ \text{GiB} \\ 40 \cdot 2^{40} \cdot 8\ \text{B} &\approx 320\ \text{TiB} \end{aligned}
Brute force over (n−1)!(n - 1)! routes needs only O(n)O(n) memory but is hopeless in time; Held–Karp is fast enough for n=20n = 20 but memory caps it there.

Example 4

Subset sum with memoisation

One memoised call

Every new (i,s)(i, s) pair costs one memo entry. The memo's size is the number of distinct pairs the search ever reaches.

How big the memo can get

∣memo∣≤min⁡ ⁣(2n,  n⋅(T+1))|\text{memo}| \le \min\!\left(2^n,\; n \cdot (T + 1)\right)
Level ii can hold at most 2i2^i different sums (one per subset of the first ii numbers), and never more than T+1T + 1 sums from 0 to the target TT once larger sums are pruned.

[3, 5, 7, 2] with target 10

Level iSums reachedEntriesCap 2i2^i
0011
13, 022
28, 3, 5, 044
38, 3, 5, 7, 058
12 entries and no memo hits: distinct numbers make almost every sum new. At level 3 the sums 15 and 12 overshoot the target and are pruned, so the row stops at 5.

Comparison

O(2ⁿ) next to other space classes

Spacen = 10n = 20n = 30
O(1)O(1)8 B8 B8 B
O(log⁡n)O(\log n)27 B35 B40 B
O(n)O(n)80 B160 B240 B
O(n2)O(n^2)800 B3.2 KB7.2 KB
O(2n)O(2^n)8 KiB8 MiB8 GiB
8 bytes per entry. Every polynomial row stays tiny; the exponential row goes from a rounding error to the whole machine.

Exponential overtakes every polynomial

lim⁡n→∞nk2n=0for every fixed k,2n>n2 for all n≥5\lim_{n \to \infty} \frac{n^k}{2^n} = 0 \quad \text{for every fixed } k, \qquad 2^n > n^2 \text{ for all } n \ge 5
No matter how high the power, 2n2^n eventually passes it. Against n2n^2 it happens at n=5n = 5.

Trade-offs

Spending less memory

Store it or stream it?

Only the first and the bitmask branches truly need exponential memory. Everything else is a design choice.
  • Generate, do not store

    A generator yields one subset at a time: same time, O(n)O(n) memory.

  • Smaller keys

    Memoise on (i,sum)(i, \text{sum}) instead of the subset: n⋅(T+1)n \cdot (T + 1) entries.

  • Smaller entries

    A bytearray is 1 byte per mask and a bitset 1 bit: 2302^{30} masks fit in 128 MiB as bits.

  • Meet in the middle

    Store only one half's results: O(2n/2)O(2^{n/2}) memory, about a million entries at n=40n = 40.

Streaming: O(n) memory

  • Each subset is built, checked and dropped.
  • Works for any nn you have time for.
  • Best when you need a count, a best one, or a yes or no.

Storing everything: O(n · 2ⁿ) memory

  • All 2n2^n subsets stay alive at once.
  • Crashes long before time runs out, around n≈25n \approx 25.
  • Only worth it when the caller truly needs the full list.

Pattern spotting

Spotting O(2ⁿ) space in code

Code shapeWhat it keepsSpace
dp = [0] * (1 << n)One entry per maskO(2n)O(2^n)
dp = [[INF] * n for _ in range(1 << n)]Mask × last elementO(n⋅2n)O(n \cdot 2^n)
result.append(current[:]) at every leafEvery subsetO(n⋅2n)O(n \cdot 2^n)
@lru_cache on f(mask, ...)One entry per reached maskup to O(2n)O(2^n)
memo[(i, s)] with s <= targetIndex × small sumO(n⋅T)O(n \cdot T)
yield subset in a backtracking loopOnly the current pathO(n)O(n)

Is this exponential space?

Memory is the number of things alive at the same moment. Count what is kept, not what is visited.

In the wild

Where exponential space shows up

  • Power set storage

    Returning all combinations, as in LeetCode-style "subsets" problems, stores 2n2^n lists.

  • TSP bitmask DP

    Route planners for small stop counts use the n⋅2nn \cdot 2^n Held–Karp table.

  • Subset sum caches

    Memoising the states of an NP-complete search can grow to 2n2^n entries.

  • State space search

    Covering, assignment and knapsack variants that track which items are used per state.

  • Truth tables

    A full truth table of a boolean function of nn inputs has 2n2^n rows.

  • Game solvers

    Solving a puzzle by caching every visited board can run out of memory before time.

Recap

Key takeaways

Key points

  • O(2ⁿ) space means memory doubles with each extra item: 2n+1=2⋅2n2^{n+1} = 2 \cdot 2^n.
  • It comes from keeping something for every subset: the subsets themselves, or one DP or memo entry per mask.
  • Storing the power set holds 2n2^n lists and n⋅2n−1n \cdot 2^{n-1} items: O(n⋅2n)O(n \cdot 2^n).
  • Held–Karp keeps n⋅2nn \cdot 2^n states for O(n2⋅2n)O(n^2 \cdot 2^n) time: 64 slots for 4 cities, about 160 MiB for 20.
  • At 8 bytes per entry: n=20n = 20 is 8 MiB, n=30n = 30 is 8 GiB, n=40n = 40 is 8 TiB. Safe up to about 20 to 25.
  • Exponential time does not force exponential space: generate lazily, key memos on small states, or meet in the middle.

Sources