How to reduce space complexity in dynamic programming
How to reduce space complexity in dynamic programming: find the window of earlier states each state reads, then keep only that window. Worked numbers for LCS and knapsack, the iteration-order trap, and what you lose when you shrink the table.
How to reduce space complexity in dynamic programming comes down to one question: which earlier states does each state actually read? Keep only that window and discard the rest. If row i reads only row i-1, two rows replace the whole grid, and sometimes one row is enough.
Why does a dynamic programming table use so much memory?
Because the standard recipe stores every state you ever compute, even though almost all of them stop being useful within a few steps. The table is a habit of teaching, not a requirement of the algorithm.
Take the longest common subsequence of two strings, one of 5000 characters and one of 4000. The textbook table has 5001 by 4001 cells, which is 20,009,001 entries. In C++ with 4-byte integers that is about 80 MB. In Python, a list of lists stores an 8-byte pointer per cell, so you are near 160 MB before counting the per-row overhead. Many judges cap memory at 256 MB, and the interpreter itself takes a slice of that. The running time is not the problem here: 20 million cell updates is acceptable. The memory is what earns you a Memory Limit Exceeded verdict.
Now look at what each cell reads. When you fill cell (i, j), the recurrence touches exactly three neighbours: (i-1, j-1), (i-1, j) and (i, j-1). Once row 3001 is complete, nothing will ever read row 2999 again. At any moment, at most two rows of 4001 cells are alive in the logical sense, which is under 0.1% of the table. The other 99.9% is dead weight that you keep paying for.
Here is the framing I use. A DP table is scaffolding around a building under construction. Workers need the floor they are pouring and the floor directly beneath it. Nobody needs the scaffolding on floor three when they are pouring floor forty, so a competent site foreman takes it down as the building rises. Space optimisation is just that: taking scaffolding down as soon as nothing above depends on it.
How do you decide which states you can throw away?
You write down the recurrence, list every offset it reads along the dimension you iterate over, and keep exactly that many layers. The largest backward offset is your window size.
In practice I run through four steps:
- Write the recurrence with explicit indices, for example dp[i][j] = f(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]).
- Pick the outer loop dimension, the one you advance slowly. Here it is i.
- Find the farthest back that dimension is read. Here it is i-1, so the window is one previous row plus the current row.
- Confirm that the fill order never needs a state outside that window. If it does, rolling will not work and you should stop.
Applied to common problems, the windows look like this. Climbing stairs and house robber read dp[i-1] and dp[i-2], so two variables replace the array and space drops from O(n) to O(1). Grid path counting reads the cell above and the cell to the left, so one row suffices. Edit distance and LCS read the previous row and the left neighbour, so two rows, or one row plus a saved diagonal. The 0/1 knapsack reads the previous item layer only, so a single array indexed by capacity is enough. Coin change is already one-dimensional, indexed by amount, and there is nothing to roll; its table size is the amount itself, and that is the honest minimum for the standard formulation (see Coin Change).
The cases where the window does not shrink matter just as much. Interval DP, where dp[l][r] is built from every split point k between l and r, reads states of all shorter lengths. There is no small window, because a state at length 900 reads states at lengths 1 through 899. Likewise, tree DP and DP over subsets read at arbitrary distances. I would rather say that plainly than pretend every DP collapses to two rows. It does not.
What does the two-row version of longest common subsequence look like?
It keeps a previous row and a current row, each as long as the shorter string, and swaps them after every character of the longer string. The time stays at m times n; only the memory changes.
def lcs_len(a, b):
if len(b) > len(a):
a, b = b, a # b is the shorter string
prev = [0] * (len(b) + 1)
for ch in a:
cur = [0] * (len(b) + 1)
for j in range(1, len(b) + 1):
if ch == b[j - 1]:
cur[j] = prev[j - 1] + 1
else:
cur[j] = max(prev[j], cur[j - 1])
prev = cur
return prev[-1]
With strings of length 5000 and 4000, the two rows hold 2 times 4001 = 8002 cells. At 8 bytes each in CPython that is about 64 KB, against roughly 160 MB for the full grid. That is a reduction of around 2500 times. The number of comparisons is unchanged at 20,000,000, so the runtime is the same to within allocation noise. Allocating a fresh list per row costs 5000 allocations of 4001 elements, which is negligible next to the inner loops. If you care, allocate the two rows once and swap references.
You can go further and use one row. The catch is that cell (i, j) needs the old value of (i-1, j-1), which the single row overwrites one step earlier. The fix is to carry that value in a variable:
def lcs_len_one_row(a, b):
if len(b) > len(a):
a, b = b, a
row = [0] * (len(b) + 1)
for ch in a:
diag = 0 # old row[j-1], from the previous character
for j in range(1, len(b) + 1):
up = row[j] # old row[j], save it before overwriting
if ch == b[j - 1]:
row[j] = diag + 1
else:
row[j] = max(up, row[j - 1])
diag = up
return row[-1]
Trace it on a = 'ab', b = 'b'. Row starts as [0, 0]. For ch = 'a', j = 1: up = 0, 'a' differs from 'b', so row[1] = max(0, row[0]) = 0, and diag becomes 0. For ch = 'b', diag resets to 0, up = 0, the characters match, so row[1] = 0 + 1 = 1. The answer is 1, which is correct. The single-row version saves another factor of two, which rarely matters. I use the two-row version by default because it is harder to get wrong, and I reach for the diagonal trick only when memory is genuinely tight.
Why does iteration direction matter when you use a single row?
Because overwriting in place means a cell can be read after it has already been updated in the same pass, and whether that is a bug or a feature depends on the problem. Backward iteration preserves old values; forward iteration exposes new ones.
The 0/1 knapsack shows it best. Each item can be used at most once. With one array indexed by capacity, the update is:
def knapsack_01(weights, values, cap):
best = [0] * (cap + 1)
for w, v in zip(weights, values):
for c in range(cap, w - 1, -1): # backward
best[c] = max(best[c], best[c - w] + v)
return best[cap]
The cell best[c - w] must hold the value from before this item was considered. Going backward from the top capacity guarantees that: when we update best[c], every smaller index is still untouched. Now flip the loop to go forward and run one item of weight 3 and value 5 with capacity 9. At c = 3, best[3] becomes 5. At c = 6, best[6] reads the already updated best[3] and becomes 10. At c = 9 it becomes 15. The code has just packed three copies of a single item. The correct answer is 5.
That wrong answer is exactly the right answer to a different problem. In the unbounded knapsack, items can be reused, and the forward loop is the correct one: it deliberately reads the updated cells. The two problems differ by one loop direction, and I have seen candidates lose twenty minutes in an interview because they pattern-matched the code and not the dependency. The variants are laid out side by side in knapsack variants.
The scale of the saving is large. For 1000 items and a capacity of 10,000, the full table has 1000 by 10,001 = 10,001,000 cells, about 40 MB at 4 bytes. The single array has 10,001 cells, about 40 KB. The work stays at 10 million updates either way.
The general rule I teach myself is this. If the cell you are writing must see the old values of cells you will write later in the same pass, loop in the direction that visits the dependencies last. If it is supposed to see new values, loop in the direction that visits them first. Draw the arrows before you write the loop, not after the test fails.
What do you lose when you shrink the table?
You lose the ability to walk backward through the table to reconstruct the actual answer, the subsequence or the set of items, rather than just its length or value. Rolling arrays give you the final number and nothing else.
For many problems that is fine, since the question asks only for a count or a maximum. When it asks for the path, you have three options.
- Store one decision bit per cell. You still run the rolling computation, but record for each cell which branch won. For LCS that is 20 million bits, or 2.5 MB, instead of 80 MB of integers. For the knapsack example it is 10 million bits, about 1.25 MB. The space is still O(mn) asymptotically, but the constant is 32 times smaller than for 4-byte integers, and that is often all you need.
- Use Hirschberg's divide and conquer. It computes the LCS forward on the first half of one string and backward on the second half, finds the split point in the other string with two rolling rows, and recurses on both halves. Space is O(min(m, n)). Time is about twice the plain algorithm, because the work forms a geometric series: mn + mn/2 + mn/4 and so on, which sums to 2mn. For our strings that is about 40 million updates. It is a real algorithm and a pleasant one, but it is not something to write from scratch in a forty-five-minute interview unless you have done it before.
- Recompute on demand. Keep checkpoints, for example every 64th row, and recompute the rows between checkpoints when walking back. It trades time for space on a dial you control.
Top-down memoisation deserves a separate warning. A recursive solution fills states in an order set by the call stack, not by you, so you cannot cleanly discard a row. You can bound a cache with eviction, but then correctness depends on never re-requesting an evicted state. If you intend to roll the table, write the bottom-up version, where you own the loop order. The trade-offs between the two styles are covered in memoisation vs tabulation.
Which space-reduction technique should you pick?
Pick the weakest optimisation that fits the memory limit. Each step down in space costs you either clarity, the ability to reconstruct, or time, so go only as far as the constraint forces you.
| Technique | Space (LCS, m by n) | Time | Can rebuild the path? | Main risk |
|---|---|---|---|---|
| Full table | O(mn), about 80 MB for 5000 by 4000 in C++ | O(mn) | Yes, by walking back | Memory limit exceeded |
| Two rolling rows | O(min(m, n)), about 32 KB at 4 bytes | O(mn) | No | Forgetting to swap or reset rows |
| One row plus diagonal variable | O(min(m, n)), about half of two rows | O(mn) | No | Overwriting a value you still need |
| Rolling rows plus decision bits | O(mn) bits, about 2.5 MB | O(mn) | Yes | Bit-packing bugs |
| Hirschberg | O(min(m, n)) | About 2 times O(mn) | Yes | Implementation complexity |
In interviews, my advice is to write the full-table solution first, get it correct, state its complexity, and only then mention that the dependency window allows rolling. Interviewers often ask for exactly that follow-up, and a correct O(mn) solution that you then compress is stronger than a half-working compressed one. In production code the order reverses slightly: check the dimensions first. If the table is 300 by 300, 90,000 cells, the optimisation is not worth the readability you spend on it. If the table is 50,000 by 50,000, it is not a question of taste; 2.5 billion cells do not fit anywhere, and you need the window.
One more habit pays off. Before you roll anything, write a tiny brute-force or full-table version and compare outputs on a few hundred random small inputs. Rolling-array bugs are almost always off-by-one in what gets overwritten, and they tend to produce answers that are plausible but wrong, which is the worst kind of bug for a quick eyeball test to catch. Random comparison against the slow version catches them in seconds.
Frequently asked questions
Does reducing space complexity in dynamic programming make the code faster?
Usually not in the big-O sense, since you still compute every state. In practice it can help a little, because two small rows fit in CPU cache while a 160 MB table does not, so cache misses drop. Treat any speedup as a bonus rather than the reason to do it.
Can every dynamic programming problem be reduced to O(n) space?
No. It works when each state reads only a bounded window of earlier layers, as in LCS, edit distance, knapsack and grid paths. Interval DP and subset DP read from far away, so their tables cannot be rolled without changing the algorithm.
Should I optimise space in a coding interview?
Only after the straightforward solution is correct, and ideally when asked or when the constraints demand it. State the dependency window out loud, then compress. For practice on exactly this move, solve the full-table version of Longest Common Subsequence first and then roll it down to a single row.