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 (covered earlier in this tutorial), and apply rolling rows. The techniques so far shrink a table along the direction the loop moves. This chapter shrinks it in a different way. It removes a whole dimension when that dimension's value can always be computed from the others.
The Core Idea: Invariants Between State Components
A DP state is a tuple of values, such as (i, j, k). Each component usually adds a factor to the table size. Sometimes the transitions keep a fixed relationship between components, for example k == i + j in every reachable state. When that holds, k adds no information. It is a function of i and j, and storing it multiplies memory by the size of its range for nothing.
A dimension is redundant when, for every reachable state, its value equals f(other components) for some function f you can compute cheaply. The test is about reachable states. A table indexed by (i, j, k) has room for states where k != i + j, but if no transition ever produces them, those cells stay at their initial value forever.
Example 1: Interleaving Strings
The problem: given strings a, b, and s, decide whether s can be formed by interleaving a and b while keeping each one's character order. A natural first state is "i characters of a and j of b have been used, and k characters of s have been matched."
def is_interleave_3d(a, b, s):
n, m = len(a), len(b)
if n + m != len(s):
return False
L = n + m
dp = [[[False] * (L + 1) for _ in range(m + 1)] for _ in range(n + 1)]
dp[0][0][0] = True
for i in range(n + 1):
for j in range(m + 1):
for k in range(L + 1):
if not dp[i][j][k] or k == L:
continue
if i < n and a[i] == s[k]:
dp[i + 1][j][k + 1] = True
if j < m and b[j] == s[k]:
dp[i][j + 1][k + 1] = True
return dp[n][m][L]
print(is_interleave_3d("aab", "axy", "aaxaby")) # True
print(is_interleave_3d("aab", "axy", "abaaxy")) # FalseEvery transition increases k by exactly one and increases exactly one of i or j by one. Starting from (0, 0, 0), the invariant k == i + j therefore holds in every reachable state. The table has (n+1)(m+1)(n+m+1) cells, but only (n+1)(m+1) of them can ever be True.
Dropping k and computing i + j where it is needed gives the standard 2D solution:
def is_interleave(a, b, s):
n, m = len(a), len(b)
if n + m != len(s):
return False
dp = [[False] * (m + 1) for _ in range(n + 1)]
dp[0][0] = True
for i in range(n + 1):
for j in range(m + 1):
k = i + j # derived, not stored
if i > 0 and dp[i - 1][j] and a[i - 1] == s[k - 1]:
dp[i][j] = True
if j > 0 and dp[i][j - 1] and b[j - 1] == s[k - 1]:
dp[i][j] = True
return dp[n][m]
print(is_interleave("aab", "axy", "aaxaby")) # True
print(is_interleave("aab", "axy", "abaaxy")) # FalseMemory drops from O(nm(n+m)) to O(nm). Time drops by the same factor, because the 3D version also loops over every k. The reductions also stack. Row i reads only rows i and i-1, so you can apply the rolling-row technique next and reach O(m).
Example 2: Two Walkers on a Grid
Two walkers start at the top-left of an n x n grid of non-negative values and move only right or down to the bottom-right. They collect the value of every cell they visit, and a cell visited by both counts once. The goal is to maximize the total.
If the walkers move in lockstep, a full state is (t, r1, c1, r2, c2): the step number and both positions. That is O(n^5) cells. Each step moves a walker one cell right or down, so after t steps a walker at row r must be in column t - r. Both columns are derivable:
c1 = t - r1c2 = t - r2
The state collapses to (t, r1, r2), which is O(n^3). The only dependency on t is on t - 1, so one 2D layer per step is enough and memory is O(n^2).
def max_two_paths(grid):
n = len(grid)
NEG = float('-inf')
dp = [[NEG] * n for _ in range(n)]
dp[0][0] = grid[0][0]
for t in range(1, 2 * n - 1):
new = [[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 = dp[r1][r2] # both moved right
if r1 > 0:
best = max(best, dp[r1 - 1][r2]) # walker 1 moved down
if r2 > 0:
best = max(best, dp[r1][r2 - 1]) # walker 2 moved down
if r1 > 0 and r2 > 0:
best = max(best, dp[r1 - 1][r2 - 1])
if best == NEG:
continue
gain = grid[r1][c1]
if r1 != r2: # same row at same t means same cell
gain += grid[r2][c2]
new[r1][r2] = best + gain
dp = new
return dp[n - 1][n - 1]
print(max_two_paths([[1, 2], [3, 4]])) # 10
print(max_two_paths([[0, 1, 1], [1, 0, 1], [1, 1, 0]])) # 4The derived dimension also simplifies the collision check. In the 5D version you compare both coordinates. Here, r1 == r2 at the same t forces c1 == c2, so comparing rows is enough.
The bounds lo and hi come from the derived columns. A row is valid only if its derived column t - r lies in [0, n-1]. That gives r >= t - n + 1 and r <= t. If you forget this, the code indexes grid with a negative column, which Python accepts silently. It reads from the wrong end of the row and returns a wrong answer without any error.
Example 3: A Counter Hidden in Another Component
Sometimes the derivable value is a count that another component already encodes. In the job-assignment problem, workers take jobs in order, and the set of taken jobs is a bitmask. The index of the next worker equals the number of jobs taken, which is the popcount of the mask. A state (i, mask) therefore collapses to (mask), which cuts the table from n·2^n to 2^n entries. The bitmask chapter works through this case in full. Here it serves as one more instance of the same pattern.
Where Derivable Dimensions Come From
| Source of the invariant | Typical state | Derived component | Saving |
|---|---|---|---|
| Lengths that add up | `(i, j, k)` over two inputs and a merged output | `k = i + j` | factor of n+m |
| Lockstep movement on a grid | `(t, r, c)` with unit steps | `c = t - r` | factor of n per walker |
| Items consumed equal items counted | `(i, mask)` with one item per step | `i = popcount(mask)` | factor of n |
| Fixed total budget | `(used, remaining)` | `remaining = total - used` | factor of the budget range |
| Prefix position and split counts | `(pos, zeros, ones)` in a binary prefix | `ones = pos - zeros` | factor of n |
A practical way to find these is to list, for each component, how every transition changes it. If two or more components change in a fixed linear combination at every transition, such as "k goes up by 1 exactly when i + j goes up by 1", and they start in a consistent state, then one of them can be dropped.
Failure Modes
The invariant breaks on one transition
A dimension is derivable only if every transition preserves the relation. Suppose a variant of the grid problem lets a walker wait in place for a step. Then c = t - r no longer holds, and dropping c silently merges different states. Check each transition, including rare ones such as skips, waits, and resets.
Correlated values are not derivable values
In 0/1 knapsack, total weight tends to grow with the item index, but it is not a function of it. Two different subsets of the first i items can have different weights. A dimension is redundant only when its value is fully determined, not merely likely.
Initial states outside the invariant
The relation must hold at the base case too. If you seed the interleaving DP with dp[0][0] = True but your derived index assumes k = i + j + 1, every comparison reads the wrong character. Write the invariant down explicitly and check that the base case satisfies it.
Derived indices out of range
Before, the loop bounds kept every stored index in range. A derived index has no loop of its own guarding it, so you must restrict the loops over the stored components so that every derived value is valid. That is what lo and hi do in the grid example.
Losing information needed for reconstruction
Dropping a derivable dimension never loses information, because you can recompute the value. That distinguishes it from rolling rows, which throw away layers you might need to rebuild the solution later. Any path traced through the reduced table can be expanded back to full states by recomputing the derived components.
Exercise
A DP over a string of length n uses the state (pos, opened, closed), where pos characters have been processed, each one either "(" or ")", and opened and closed count each kind. Which dimension can you drop, what is the new table size, and what bound must you add to the loops?
Show answer
Every character is exactly one "(" or one ")", so closed = pos - opened. Drop closed. The table becomes (n+1) x (n+1) instead of (n+1)^3. Loop opened from 0 to pos, so the derived closed = pos - opened is never negative. If the problem also needs a valid prefix, require opened >= closed, which means opened >= pos / 2.
Exercise
In the two-walker grid problem, suppose walker 2 may move two cells right in a single step while walker 1 still moves one cell right or down per step. Can you still drop c2? Can you still drop c1?
Show answer
You can still drop c1, because walker 1's moves preserve r1 + c1 = t. You cannot drop c2. After t steps walker 2 can satisfy r2 + c2 = t + x for different numbers x of double moves, so c2 is not a function of t and r2. You must keep c2, or keep the count of double moves, as a real dimension.
Exercise
Starting from the 2D is_interleave function, how much memory does the solution use after you also apply rolling rows, and which loop dependency makes that possible?
Show answer
dp[i][j] reads only dp[i-1][j] and dp[i][j-1]. That is the previous row at the same column and the current row to the left. A single array of length m+1, updated left to right, keeps dp[i-1][j] at index j until it is overwritten and already holds dp[i][j-1] at index j-1. Memory becomes O(m). Swapping the strings so that b is the shorter one gives O(min(n, m)).