Sub topic 8
Removing State Dimensions You Can Derive
This chapter assumes you can write a bottom-up DP table, read a recurrence's dependency pattern, and roll a table over its outer index. Those topics were covered in the earlier chapters on dependency analysis and rolling rows.
Some state components are not independent. If one coordinate always equals a function of the others for every reachable state, it does not need its own dimension in the table. Dropping it shrinks the table by a full factor of that dimension's size, and the rest of the algorithm stays the same.
The Test: Is This Coordinate a Function of the Others?
Write out the full state tuple and look for an invariant that holds in every reachable state. These invariants turn up often:
| Invariant | Derived coordinate | Example |
|---|---|---|
| Steps taken equals row plus column on a right/down grid | Column = `t - r` | Two walkers on a grid |
| Items processed equals bits set in a subset mask | Worker index = popcount(mask) | Assignment problem |
| Remaining budget equals total minus amount spent | Remaining = `B - spent` | Budgeted path problems |
| Two pointers advance together | `j = i + offset` | Fixed-gap comparisons |
If the invariant holds, compute the derived coordinate inside the loop instead of indexing it.
Worked Example: Two Walkers on a Grid
Two walkers start at the top-left of an n × n grid of non-negative values. Each one moves only right or down until it reaches the bottom-right corner. They collect the value of every cell they visit, and a cell visited by both counts only once. The goal is the maximum total.
The obvious state is both positions, (r1, c1, r2, c2), which needs n⁴ entries. If both walkers move in lockstep, then after t moves each one satisfies r + c = t. That makes c1 and c2 derivable, so the state becomes (t, r1, r2). Each step reads only step t - 1, which means we can also roll over t.
def max_two_paths(grid):
n = len(grid)
NEG = float('-inf')
prev = [[NEG] * n for _ in range(n)]
prev[0][0] = grid[0][0]
for t in range(1, 2 * n - 1):
curr = [[NEG] * n for _ in range(n)]
lo, hi = max(0, t - n + 1), min(n - 1, t)
for r1 in range(lo, hi + 1):
c1 = t - r1
for r2 in range(lo, hi + 1):
c2 = t - r2
best = max(
prev[r1][r2],
prev[r1 - 1][r2] if r1 else NEG,
prev[r1][r2 - 1] if r2 else NEG,
prev[r1 - 1][r2 - 1] if r1 and r2 else NEG,
)
if best == NEG:
continue
gain = grid[r1][c1]
if r1 != r2:
gain += grid[r2][c2]
curr[r1][r2] = best + gain
prev = curr
return prev[n - 1][n - 1]
print(max_two_paths([[1, 2], [3, 4]])) # 10The four prev lookups are the four combinations of "came from the left" (same row) and "came from above" (row minus one) for the two walkers. Because each column is derived, two walkers share a cell exactly when r1 == r2.
Common Errors
- Ignoring the derived coordinate's range. The column
t - rmust lie in[0, n - 1]. That is whyrruns frommax(0, t - n + 1)tomin(n - 1, t). Without these bounds you index outside the grid. - Assuming an invariant that only holds on some paths. If walkers could also move diagonally,
r + c = twould break and the column would no longer be derivable. Check that every transition preserves the invariant. - Forgetting the shared-cell rule. In the full state you compare both coordinates. In the reduced state the row alone decides whether the cells match, but only because the step counts are equal.
Exercise
A DP state is (i, j, k), where i indexes string x, j indexes string y, and every transition increments i and j together, so k = j - i stays fixed at its starting value d. Which dimension can you drop, and how large is the table afterward for strings of length m and n?
Show answer
Drop j, because j = i + d. The state becomes (i, k) when k varies across subproblems, or just i for a single fixed d. The table shrinks from about m·n·K entries to m·K, or to m entries for one fixed offset.
Exercise
In maxtwopaths, how much memory does the reduced and rolled version use compared with the naive four-coordinate table, for n = 100?
Show answer
The rolled version keeps two n × n arrays, about 2 × 10^4 entries. The naive table has n^4 = 10^8 entries, which is roughly 5,000 times more.