Sub topic 1
Where DP Memory Goes: States, Transitions, and Tables
Dynamic programming (DP) makes slow recursive solutions fast by storing answers to subproblems and reusing them. The stored answers cost memory, and the cost is often far larger than people expect. A solution that runs in a few seconds can still fail because its table does not fit in RAM.
This chapter explains where that memory goes. You will learn to describe a DP in terms of states, transitions, and tables, and to estimate the memory a table needs before you write any code. Later chapters build on this to cut the memory down.
Prerequisites
This tutorial assumes you already know the following:
- Basic dynamic programming: writing a recurrence, memoizing it top-down, and filling a table bottom-up.
- Big-O analysis of time and space.
- Arrays, nested loops, and recursion in Python or a similar language.
- Classic problems such as Fibonacci, 0/1 knapsack, and longest common subsequence (LCS).
You do not need to know any memory-reduction tricks. This chapter introduces the vocabulary that the rest of the tutorial uses.
The Three Parts of a DP
Every DP solution has three parts.
- State. A state is a tuple of parameters that identifies one subproblem. In LCS, the state
(i, j)means "the LCS length of the firsticharacters ofxand the firstjcharacters ofy." - Transition. A transition is the rule that computes a state's value from other states' values. For LCS,
dp[i][j]readsdp[i-1][j-1],dp[i-1][j], anddp[i][j-1]. - Table. The table is the data structure that holds a value for each state. It can be an array, a nested list, or a dictionary used as a memo.
Time cost is roughly number of states × work per transition. Memory cost is roughly number of states stored × bytes per stored entry. These two formulas are separate. A DP can do a lot of work per state and use little memory, or do little work per state and use a lot of memory.
The dashed arrow in the diagram is the subject of this tutorial. A full table stores every state for the whole run. Most transitions only read a small, predictable set of earlier states. If a state will never be read again, it does not need to stay in memory.
Counting States
The number of states is the product of the ranges of the state parameters. Here are the classic problems this tutorial uses:
| Problem | State | Number of states | States read per transition | Full-table memory |
|---|---|---|---|---|
| Fibonacci | `i` | `n + 1` | 2 | O(n) |
| LCS of lengths m, n | `(i, j)` | `(m + 1)(n + 1)` | 3 | O(mn) |
| Edit distance | `(i, j)` | `(m + 1)(n + 1)` | 3 | O(mn) |
| 0/1 knapsack, n items, capacity W | `(item, capacity)` | `(n + 1)(W + 1)` | 2 | O(nW) |
| Coin change ways, k coins, amount A | `(coin, amount)` | `(k + 1)(A + 1)` | 2 | O(kA) |
| Job assignment, n workers and jobs | `(worker, used_jobs_mask)` | `n · 2^n` | up to n | O(n · 2^n) |
Look at the last two columns. Each transition reads only a handful of states, but the full table keeps all of them. That difference is what later chapters exploit.
A Full Table in Practice
Here is the standard full-table LCS. It keeps every row for the entire run.
import sys
def lcs_table(x, y):
m, n = len(x), len(y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp
def table_bytes(dp):
"""Bytes used by the outer list and each row list (pointer slots only)."""
total = sys.getsizeof(dp)
for row in dp:
total += sys.getsizeof(row)
return total
dp = lcs_table("ABCBDAB", "BDCABA")
print("LCS length:", dp[-1][-1]) # 4
for size in (100, 1000, 3000):
a = "AB" * (size // 2)
b = "BA" * (size // 2)
t = lcs_table(a, b)
cells = len(t) * len(t[0])
print(f"size={size:5d} cells={cells:>10,} bytes~{table_bytes(t):>12,}")When you run it, memory grows with the square of the input size. Tripling the length from 1,000 to 3,000 multiplies the cell count by about 9. The 3,000 case takes noticeable time and around 72 MB of list slots. At 100,000 characters per string the table would hold about 10^10 cells, which comes to roughly 80 GB of pointer slots in CPython. No ordinary machine can hold that.
Bytes per Entry Matter Too
The memory formula has two factors, and the second one is often ignored. The same 10^8-state table costs very different amounts depending on how each entry is stored:
| Storage | Approximate bytes per entry | 10^8 entries |
|---|---|---|
| NumPy `int8` / C `char` | 1 | 100 MB |
| NumPy `int32` / C `int` | 4 | 400 MB |
| NumPy `int64` / C `long` | 8 | 800 MB |
| Python list of small ints | 8 (pointer) | 800 MB |
| Python list of large ints | 8 + about 28 | about 3.6 GB |
| Python `dict` memo | roughly 50–100+ including key tuple | 5–10+ GB |
Choosing a smaller value type is a constant-factor saving. It helps, but it never changes the big-O memory. The techniques in this tutorial change the number of states you keep, which matters more.
Where Else Memory Goes
The table is the largest cost, but there are others.
- Reconstruction data. If you need the optimal solution itself (the actual subsequence, or the chosen items), the usual method walks back through the full table. Throwing rows away makes that walk impossible unless you plan for it. A later chapter covers this trade-off.
- Memoization overhead. Top-down memoization stores states in a dictionary, which costs much more per entry than an array. It also uses the call stack. Recursion depth can reach the number of states along one chain, such as
nfor Fibonacci orm + nfor LCS. Python's default recursion limit is 1000. - Unreachable states. A full table allocates every combination of parameters, even ones the problem never reaches. Knapsack with a few huge weights may touch only a small fraction of capacities.
Common Errors
These are the mistakes intermediate programmers make most often when reasoning about DP memory:
- Confusing time and space. O(nW) time does not force O(nW) memory. The table size follows from what you keep, not from how much work you do.
- Counting cells but ignoring per-entry cost. A dictionary memo with tuple keys can cost ten times more than an array of the same states.
- Forgetting the boundary row and column. Tables sized
(m + 1) × (n + 1)include base cases. Off-by-one sizing causes index errors or wrong answers. - Building rows by aliasing.
[[0] * (n + 1)] * (m + 1)makes every row the same list object. Writing to one row changes them all. Use a list comprehension, as inlcs_table. - Assuming the memo is cheaper because it skips states. It is cheaper only when many states are unreachable. Otherwise dictionary overhead makes it more expensive.
What Comes Next
The central question of this tutorial is which stored states a transition will read again. The next chapter shows how to read that dependency pattern from a recurrence. Every later technique relies on it, including rolling variables, two-row arrays, in-place updates, and dropping state dimensions.
Exercise
A 0/1 knapsack has 200 items and capacity W = 1,000,000. You store the full table as a NumPy int64 array of shape (n + 1, W + 1). Roughly how much memory does it use, and what does each transition read?
Show answer
The table has 201 × 1,000,001 ≈ 2.01 × 10^8 cells. At 8 bytes each that is about 1.6 GB. Each transition for dp[i][c] reads dp[i-1][c] and dp[i-1][c - w_i], both from the previous item's row. So at any moment only the previous row is needed to compute the current one, which hints that most of the table is stored for no reason.
Exercise
The job-assignment DP uses state (worker, usedjobsmask) for n = 20. How many states does the full table have, and how much memory is that at 4 bytes per entry?
Show answer
The table has n · 2^n = 20 × 1,048,576 = 20,971,520 states. At 4 bytes each that is about 84 MB. A later chapter shows that the worker index equals the number of set bits in the mask. Dropping that dimension leaves 2^20 states, about 4 MB.
Exercise
Why does dp = [[0] 5] 3 give wrong results in a 2D DP, and how do you fix it?
Show answer
The outer multiplication repeats a reference to the same inner list three times, so all three rows are one object and a write to dp[1][2] also appears in dp[0][2] and dp[2][2]. Fix it with dp = [[0] * 5 for _ in range(3)], which creates a separate list for each row.