Sub topic 12
Shrinking the table: rolling arrays and variables
A filled DP table often holds far more than the final answer needs. This chapter shows how to keep only the part of the table that later cells still read. You will cut Fibonacci from O(n) to O(1) space and the longest common subsequence (LCS) from O(m·n) to O(min(m, n)). You will also see where the method breaks.
This chapter assumes you can already write a tabulated (bottom-up) solution, read a recurrence and its fill order, and work out time and space as "number of states times work per state." The LCS table from the two-dimensional chapter is used throughout.
The core idea: a recurrence's dependency footprint
Every recurrence reads a fixed set of earlier cells. That set is its dependency footprint. Once the fill order moves past the point where a cell can still be read, the cell is dead. Its memory can be reused.
Three steps decide how small the table can get:
- Write the recurrence and list every cell it reads, relative to the current cell.
- Look at the fill order and find the oldest cell that any future computation will still read.
- Keep everything from that cell to the current one, and nothing older.
| Recurrence | Cells read | What must stay live | Space |
|---|---|---|---|
| Fibonacci `f[i] = f[i-1] + f[i-2]` | 2 previous values | 2 scalars | O(1) |
| Coin change `dp[a] = min(dp[a-c] + 1)` | up to `max(coins)` back | a window of `max(coins) + 1` values | O(max coin) |
| LCS `dp[i][j]` from `dp[i-1][j-1]`, `dp[i-1][j]`, `dp[i][j-1]` | previous row and current row | 2 rows, or 1 row plus 1 scalar | O(n) |
| 0/1 knapsack `dp[i][c]` from `dp[i-1][c]`, `dp[i-1][c-w]` | previous row only | 1 row, filled in the right direction | O(capacity) |
Time complexity does not change in any row of this table. You do the same work per state. You just stop storing states nobody will read again.
From a table to two variables: Fibonacci
The tabulated Fibonacci stores table[0..n], but table[i] reads only table[i-1] and table[i-2]. After computing table[i], the entry table[i-2] is never touched again. Two variables can stand in for the whole table:
def fib(n):
prev, curr = 0, 1
for _ in range(n):
prev, curr = curr, prev + curr
return prev
print([fib(i) for i in range(10)]) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]The tuple assignment matters. Python evaluates the right side, (curr, prev + curr), using the old values before it rebinds either name. If you write it as two separate statements, prev = curr followed by curr = prev + curr, the second line reads the new prev, and you get powers of two instead of Fibonacci numbers.
Rolling rows: LCS in two rows
LCS fills dp[i][j] row by row. Each cell reads from the row above (dp[i-1][j-1] and dp[i-1][j]) and from the cell to its left in the current row (dp[i][j-1]). Row i-2 and everything older is dead by the time row i starts.
So two rows are enough: prev for row i-1 and curr for row i.
def lcs_length(a, b):
# Make b the shorter string so each row has min(len(a), len(b)) + 1 cells.
if len(b) > len(a):
a, b = b, a
n = len(b)
prev = [0] * (n + 1)
for i in range(1, len(a) + 1):
curr = [0] * (n + 1)
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
curr[j] = prev[j - 1] + 1
else:
curr[j] = max(prev[j], curr[j - 1])
prev = curr
return prev[n]
print(lcs_length("ABCBDAB", "BDCABA")) # 4Swapping the strings is safe because LCS length is symmetric: lcs(a, b) and lcs(b, a) have the same length. The swap puts the shorter string along the columns, so space becomes O(min(m, n)) instead of O(n).
Gotcha: aliasing the rows
A tempting "optimization" allocates curr once outside the loop and then writes prev = curr. In Python that makes both names point to the same list. From the second row on, prev[j - 1] and prev[j] read cells that this row has already overwritten, and the result is silently wrong. You have two correct options:
- Allocate a fresh
curreach row, as above. That costs O(n) allocation per row, which the O(n) row fill already pays for. - Keep two fixed lists and swap them:
prev, curr = curr, prev. This reuses memory with no aliasing. It works for LCS because everycurr[j]forj ≥ 1gets overwritten before it is read, andcurr[0]stays 0.
The modulo form
Another common way to write the same thing keeps a 2-row table and indexes it with i % 2. It looks almost exactly like the full-table code, so it is easy to convert and review:
def lcs_length_mod(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(2)]
for i in range(1, m + 1):
cur, prv = i % 2, (i - 1) % 2
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[cur][j] = dp[prv][j - 1] + 1
else:
dp[cur][j] = max(dp[prv][j], dp[cur][j - 1])
return dp[m % 2][n]
print(lcs_length_mod("ABCBDAB", "BDCABA")) # 4Generalize it to i % k when a recurrence reads back k - 1 rows.
One row plus a scalar
You can go one step further. Use a single row dp that holds a mix: cells left of j already belong to row i, and cells from j onward still belong to row i-1. At position j:
dp[j]still holds the olddp[i-1][j](above).dp[j-1]already holds the newdp[i][j-1](left).- The diagonal
dp[i-1][j-1]was overwritten one step ago, so you must save it in a variable before you overwrite it.
def lcs_length_one_row(a, b):
if len(b) > len(a):
a, b = b, a
n = len(b)
dp = [0] * (n + 1)
for i in range(1, len(a) + 1):
diag = 0 # old dp[i-1][0]
for j in range(1, n + 1):
above = dp[j] # old dp[i-1][j], about to be overwritten
if a[i - 1] == b[j - 1]:
dp[j] = diag + 1
else:
dp[j] = max(above, dp[j - 1])
diag = above # becomes dp[i-1][j-1] for the next j
return dp[n]
print(lcs_length_one_row("ABCBDAB", "BDCABA")) # 4This saves one row compared to the two-row version. The asymptotic space is the same, so the main reason to use it is that the same in-place, one-row pattern carries over to knapsack in the next chapter. There, the direction you sweep the row decides whether you read old or new values.
A sliding window: coin change
Coin change is already one-dimensional, but dp[a] reads only dp[a - c] for each coin c. The furthest it reaches back is max(coins). A ring buffer of size max(coins) + 1 holds every value that can still be read:
def min_coins_window(coins, amount):
INF = float('inf')
k = max(coins) + 1
ring = [INF] * k
ring[0] = 0
for a in range(1, amount + 1):
best = INF
for c in coins:
if c <= a and ring[(a - c) % k] + 1 < best:
best = ring[(a - c) % k] + 1
ring[a % k] = best # overwrites dp[a - k], which no coin can reach
result = ring[amount % k]
return result if result != INF else -1
print(min_coins_window([1, 5, 11], 15)) # 3 (5 + 5 + 5)
print(min_coins_window([2], 3)) # -1
print(min_coins_window([1, 2, 5], 10**6)) # 200000This is worth doing only when amount is much larger than the largest coin. For typical inputs the plain O(amount) list is simpler to read and debug. Note that best is computed in a local variable and written once. Writing straight into ring[a % k] while you loop over coins would be harmless here, but the habit of computing first and writing once avoids read-after-write mistakes in harder recurrences.
What you give up
Space optimization has real costs. Decide on them before you apply it.
| Concern | Full table | Rolled table |
|---|---|---|
| Final value | Yes | Yes |
| Reconstruct the actual solution by tracing back | Yes | No, the cells the trace needs are gone |
| Inspect intermediate states while debugging | Easy | Hard |
| Works with memoization | Natural | Rarely; a cache has no fill order to roll along |
| Code clarity | Mirrors the recurrence | Needs care with update order |
Losing traceback is the big one. The LCS traceback in the previous chapter walks from dp[m][n] up to row 0, so it needs every row. If you need both the subsequence and O(n) memory, look up Hirschberg's algorithm. It uses divide and conquer to recover the subsequence in linear space, at about twice the time. A simpler compromise is to store one compact decision per cell (for example, 2 bits for "diagonal/up/left") instead of full integers. That is still O(m·n) space, but with a much smaller constant.
Rolling also depends on a fixed fill order. A memoized solution visits states in whatever order the recursion reaches them, so there is no point at which you know a row is dead. Convert to tabulation first, then shrink.
Use this checklist when you decide:
- Do I need only the optimal value, or also the choices that produce it?
- Is the full table actually too big? An m·n table of 10^4 × 10^4 Python ints is far too big. One of 500 × 500 is fine.
- Can I name the oldest cell the recurrence ever reads? If not, I cannot safely shrink.
Exercise
A recurrence over a grid is dp[i][j] = dp[i-1][j] + dp[i][j-1] (count paths moving only down or right), with dp[0][j] = dp[i][0] = 1. Write it with a single row of length n and state why the left-to-right sweep is correct.
Show answer
Use row = [1] * n, then for i in range(1, m): for j in range(1, n): row[j] += row[j - 1]. Return row[n - 1]. Before the update, row[j] still holds dp[i-1][j] (above). Sweeping left to right means row[j - 1] was already updated this row, so it holds dp[i][j-1] (left). Those are exactly the two values the recurrence needs, so no extra scalar is required.
Exercise
In lcslengthone_row, a student moves the line "diag = above" to just before the if statement. What goes wrong, and on which input does it first show up?
Show answer
Then diag equals dp[i-1][j] (above) instead of dp[i-1][j-1] when the match branch reads it. A match now adds 1 to the wrong cell, which can count one character of a twice. For a = "AA" and b = "A", the correct answer is 1. The modified code computes dp[1] = 1 on the first row, and on the second row diag becomes 1 before the match, so it returns 2.
Exercise
You need the actual longest common subsequence of two strings of length 50,000 each, and memory allows about 100 MB. Is a full integer table feasible in Python, and what would you do?
Show answer
No. The table has about 2.5 billion cells, and a Python list of lists uses at least 8 bytes per cell for pointers alone, so it needs well over 20 GB. A rolled table gives the length in O(n) space but loses the traceback. To recover the subsequence, use Hirschberg's linear-space divide-and-conquer algorithm, which needs O(n) memory and roughly twice the time.