Sub topic 2
Reading the Dependency Pattern of a Recurrence
This chapter assumes you can write a bottom-up DP table, read a recurrence such as the one for longest common subsequence (LCS), and reason about Big-O space. Every memory reduction later in this tutorial rests on one question: when the algorithm computes a state, which earlier states does it read? The answer is the recurrence's dependency pattern. Once you have it written down, picking a technique is mostly a matter of matching it to a known pattern.
What a dependency pattern is
A dependency pattern is the set of offsets from the current state to the states its transition reads. For a 2D state dp[i][j], an offset (-1, 0) means "reads dp[i-1][j]." Some people call this set the recurrence's stencil.
Here are the patterns of the classic problems:
| Problem | Recurrence reads | Offsets |
|---|---|---|
| Fibonacci | `f[i-1]`, `f[i-2]` | `-1`, `-2` |
| LCS / edit distance | `dp[i-1][j-1]`, `dp[i-1][j]`, `dp[i][j-1]` | `(-1,-1)`, `(-1,0)`, `(0,-1)` |
| 0/1 knapsack | `dp[i-1][c]`, `dp[i-1][c-w]` | `(-1,0)`, `(-1,-w)` |
| Unbounded coin change | `dp[i-1][a]`, `dp[i][a-coin]` | `(-1,0)`, `(0,-coin)` |
| Interval DP (e.g. matrix chain) | `dp[i][k]`, `dp[k+1][j]` for all `k` | variable, both directions |
The table makes the memory question concrete. Anything the pattern never reaches again can be thrown away.
Three properties to extract
For each dimension you plan to compress, read three things off the offsets.
- Reach along the outer loop. This is the largest look-back in the dimension your outer loop walks. Fibonacci reaches back 2. LCS and 0/1 knapsack reach back 1 row. If the reach is
k, you only need the lastklayers plus the one you are filling. - Same-layer reads and their direction. An offset of
0in the outer dimension means the transition reads values from the layer it is currently writing. Coin change reads(0, -coin), which lies to the left in the current row. LCS reads(0, -1). These reads fix the order you must fill a layer in. - Cross-layer reads that are not straight above. Offsets such as
(-1,-1)or(-1,-w)read the previous layer at a different column. When you squeeze two layers into one array, those cells may already be overwritten by the time you need them.
The three properties correspond to later chapters. Reach decides between rolling variables, two rows, or modulo buffers. Same-layer direction and off-column cross-layer reads decide the loop direction and whether you need a saved diagonal value.
Tracing dependencies instead of guessing
For a simple recurrence you can read the offsets straight off the formula. For a branchy or unfamiliar one, instrument the table and record what it actually reads. The tracer below logs every read relative to the cell being computed.
class Tracer:
def __init__(self, rows, cols):
self.data = [[0] * cols for _ in range(rows)]
self.offsets = set()
self.current = None
def read(self, i, j):
ci, cj = self.current
self.offsets.add((i - ci, j - cj))
return self.data[i][j]
def write(self, i, j, value):
self.data[i][j] = value
def lcs_traced(x, y):
m, n = len(x), len(y)
t = Tracer(m + 1, n + 1)
for i in range(1, m + 1):
for j in range(1, n + 1):
t.current = (i, j)
if x[i - 1] == y[j - 1]:
t.write(i, j, t.read(i - 1, j - 1) + 1)
else:
t.write(i, j, max(t.read(i - 1, j), t.read(i, j - 1)))
return t.data[m][n], t.offsets
def knapsack_traced(weights, values, capacity):
n = len(weights)
t = Tracer(n + 1, capacity + 1)
for i in range(1, n + 1):
w, v = weights[i - 1], values[i - 1]
for c in range(capacity + 1):
t.current = (i, c)
best = t.read(i - 1, c)
if c >= w:
best = max(best, t.read(i - 1, c - w) + v)
t.write(i, c, best)
return t.data[n][capacity], t.offsets
length, offsets = lcs_traced("ABCBDAB", "BDCABA")
print(length, sorted(offsets))
# 4 [(-1, -1), (-1, 0), (0, -1)]
best, offsets = knapsack_traced([1, 3, 4], [15, 20, 30], 4)
print(best, sorted(offsets))
# 35 [(-1, -4), (-1, -3), (-1, -1), (-1, 0)]The two outputs say different things.
- LCS reads only row offsets
0and-1. It has a same-row read to the left(0,-1)and an off-column cross-row read(-1,-1). So two rows always work, and a single row needs extra care for the diagonal. - 0/1 knapsack reads only row offset
-1, never the current row. Its column offsets depend on the item weights, but they are all zero or negative. So every read points to the previous row at the same column or to its left. That fact is the reason a single array filled from right to left works, which a later chapter shows in detail.
Evaluation order is part of the pattern
Offsets only mean something relative to a loop order. A bottom-up fill is valid when every offset points to a state that was computed earlier. For row-major loops (i outer, j inner), that means each offset is either negative in i, or zero in i and negative in j. LCS's offsets all satisfy this rule.
The loop order also decides which dimension you can compress. You compress the outer dimension, because that is the one where old layers become dead. In LCS you can make either string the outer loop. Making the longer string outer leaves rows the length of the shorter one, which gives O(min(m, n)) space. Some recurrences allow other sweeps. LCS cells on the same anti-diagonal (i + j constant) do not depend on each other, so a fill by anti-diagonals is also valid. It keeps three diagonals instead of two rows.
Edge cases that change the analysis
Unbounded reach. Interval DP reads dp[i][k] and dp[k+1][j] for every split point k. If you fill by interval length, a cell reads all shorter lengths, not just the previous one. No fixed number of layers is enough, so rolling arrays do not apply. In that case, look for a derivable dimension or a sparse set of reachable states.
Data-dependent offsets. In knapsack the column offset -w changes per item. What matters for compression is the sign of the offsets. Their size does not matter. If one transition read forward (c + w) and another read backward, no single fill direction would be safe.
Hidden dependencies in the answer. Some problems take the answer as max over the whole table instead of from the final cell. A common example is the longest common substring. The final answer then depends on every state. You can still compress, but you must fold the maximum into a running variable as you go.
Reconstruction. The pattern tells you what the value computation needs. Recovering the actual solution (which items were taken, which characters match) needs back-pointers or the full table. Compressing to the minimum pattern throws that information away. A later chapter deals with getting it back.
Top-down memoization. A memoized recursion has the same pattern, but the order of evaluation is implicit and the cache usually keeps every state forever. Dependency analysis tells you which entries could be evicted. A plain lru_cache(None) will not evict them.
Summary of the workflow
- Write the recurrence and list every offset, across every branch.
- Choose the loop order and confirm all offsets point to earlier states.
- Measure the reach along the outer dimension.
- Note same-layer reads and off-column cross-layer reads, with their directions.
- Check whether the final answer or a reconstruction step needs more than the last layer.
Exercise
The recurrence for counting paths in a grid with obstacles is dp[i][j] = dp[i-1][j] + dp[i][j-1] (or 0 on an obstacle). List its offsets, state its reach along i, and say whether a single array of length (columns) filled left to right is correct.
Show answer
The offsets are (-1, 0) and (0, -1), and the reach along i is 1. A single array filled left to right is correct. Before you overwrite dp[j], it still holds the previous row's value, which is the (-1, 0) read. dp[j-1] has already been updated for the current row, which is the (0, -1) read. There is no diagonal read, so no saved value is needed.
Exercise
A recurrence reads f[i-1], f[i-3], and f[i-7]. How many previous values must you keep, and why can you not simply keep three variables?
Show answer
The reach is 7, so you must keep the last 7 values (indices i-7 through i-1). Only three of them are read in any one step, but each value stays live until it has been read as f[i-7]. A buffer of size 7 indexed with modulo works.
Exercise
You run the Tracer on an LCS implementation with x = "AAA" and y = "BBB" and get offsets {(-1, 0), (0, -1)}. Your teammate concludes the single-row version needs no saved diagonal. What is wrong with that conclusion?
Show answer
The strings never match, so the match branch, which reads (-1, -1), never ran. The true pattern is the union over all branches: (-1, -1), (-1, 0), (0, -1). A single-row version must save the diagonal value before it is overwritten.