O(2ⁿ) exponential space
easy 15 minO(2ⁿ) space means the memory doubles every time one more item is added.
Video lesson · Chapter 1 of 6
One drawer for every subset
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.
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 items have subsets. Store one thing per subset and you need slots.
+1 item, ×2 memory
Going from to doubles the table, because .
Safe up to about 20 to 25
entries is 8 MiB. is 8 GiB, more than most machines will give one program.
Doubling, written out
The picture
Why 2ⁿ: the include or exclude tree
Include or exclude, for A and B
Two choices per item
Scale
The memory danger zone
| n | entries | At 8 bytes each | Practical? |
|---|---|---|---|
| 10 | 1,024 | 8 KiB | Yes |
| 15 | 32,768 | 256 KiB | Yes |
| 20 | 1,048,576 | 8 MiB | Yes |
| 25 | 33,554,432 | 256 MiB | Borderline |
| 30 | 1,073,741,824 | 8 GiB | No |
| 40 | about 1.1 trillion | 8 TiB | No |
Memory at n = 20, 30 and 40
Example 1
Storing the power set
- 1Start[ { } ]: 1 subset
- 2Add Acopy each, add A: 2 subsets
- 3Add Bcopy each, add B: 4 subsets
- 4Add Ccopy each, add C: 8 subsets
Every item makes a copy of everything stored so far, which is exactly doubling.
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 itemsOutput size: more than 2ⁿ
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 items the masks run from 0 to , so the table has entries before it holds any extra dimension.
A mask is a subset and an index
| Mask | Binary (C B A) | Subset | Mask | Binary (C B A) | Subset |
|---|---|---|---|---|---|
| 0 | 000 | { } | 4 | 100 | {C} |
| 1 | 001 | {A} | 5 | 101 | {A, C} |
| 2 | 010 | {B} | 6 | 110 | {B, C} |
| 3 | 011 | {A, B} | 7 | 111 | {A, B, C} |
dp[5] is the answer for {A, C}; dp = [0] * (1 << n) reserves a slot for every subset.Table size
Example 3
Held–Karp: TSP with a dp[mask][city] table
States and time
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 earlier cities. For 4 cities the table has slots.How the table is filled
prev row is ready when it is needed. Every row must stay in memory until the end.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 -> AHeld–Karp memory at n = 20, 30 and 40
Example 4
Subset sum with memoisation
One memoised call
How big the memo can get
[3, 5, 7, 2] with target 10
| Level i | Sums reached | Entries | Cap |
|---|---|---|---|
| 0 | 0 | 1 | 1 |
| 1 | 3, 0 | 2 | 2 |
| 2 | 8, 3, 5, 0 | 4 | 4 |
| 3 | 8, 3, 5, 7, 0 | 5 | 8 |
Comparison
O(2ⁿ) next to other space classes
| Space | n = 10 | n = 20 | n = 30 |
|---|---|---|---|
| 8 B | 8 B | 8 B | |
| 27 B | 35 B | 40 B | |
| 80 B | 160 B | 240 B | |
| 800 B | 3.2 KB | 7.2 KB | |
| 8 KiB | 8 MiB | 8 GiB |
Exponential overtakes every polynomial
Trade-offs
Spending less memory
Store it or stream it?
Generate, do not store
A generator yields one subset at a time: same time, memory.
Smaller keys
Memoise on instead of the subset: entries.
Smaller entries
A bytearray is 1 byte per mask and a bitset 1 bit: masks fit in 128 MiB as bits.
Meet in the middle
Store only one half's results: memory, about a million entries at .
Streaming: O(n) memory
- Each subset is built, checked and dropped.
- Works for any 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 subsets stay alive at once.
- Crashes long before time runs out, around .
- Only worth it when the caller truly needs the full list.
Pattern spotting
Spotting O(2ⁿ) space in code
| Code shape | What it keeps | Space |
|---|---|---|
dp = [0] * (1 << n) | One entry per mask | |
dp = [[INF] * n for _ in range(1 << n)] | Mask × last element | |
result.append(current[:]) at every leaf | Every subset | |
@lru_cache on f(mask, ...) | One entry per reached mask | up to |
memo[(i, s)] with s <= target | Index × small sum | |
yield subset in a backtracking loop | Only the current path |
Is this exponential space?
In the wild
Where exponential space shows up
Power set storage
Returning all combinations, as in LeetCode-style "subsets" problems, stores lists.
TSP bitmask DP
Route planners for small stop counts use the Held–Karp table.
Subset sum caches
Memoising the states of an NP-complete search can grow to 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 inputs has 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: .
- It comes from keeping something for every subset: the subsets themselves, or one DP or memo entry per mask.
- Storing the power set holds lists and items: .
- Held–Karp keeps states for time: 64 slots for 4 cities, about 160 MiB for 20.
- At 8 bytes per entry: is 8 MiB, is 8 GiB, 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.