Q&A-1When does a dynamic program need a second state dimension, and how do you decide what the second index should encode?
Answer
A DP needs a second dimension when the index you have does not fully determine the subproblem: two subproblems at the same index can still be asking different questions. That is the test. Fix every index you already have, and ask whether the answer can still vary. If it can, you are missing a dimension.
LCS is the clean case. "The LCS of s up to position i" is ambiguous, because the answer also depends on how much of t you have consumed. So the state is dp[i][j] = length of the LCS of s[:i] and t[:j]. Edit distance has the same shape. Zero-one knapsack after i items depends on how much capacity is left, so dp[i][w]. A grid path depends on both coordinates, so dp[i][j]. In each case the second index is exactly the quantity the first index does not pin down: position in the second sequence, remaining budget, the other coordinate.
Before writing any recurrence I write one sentence: dp[i][j] is ____. Base cases are then the zero edges (i = 0 or j = 0), and the state count is the product of the ranges: two length-1000 strings give 1001 x 1001, about 1.0M cells.
Storage is a separate decision from state. Rolling the table changes memory, not meaning:
# LCS, rolling: prev is row i-1 while cur is row i
prev = [0] * (m + 1)
for i in range(1, n + 1):
cur = [0] * (m + 1)
for j in range(1, m + 1):
if s[i - 1] == t[j - 1]:
cur[j] = prev[j - 1] + 1
else:
cur[j] = max(prev[j], cur[j - 1])
prev = curStill dp[i][j] conceptually, but memory falls from roughly 4 MB to 8 KB for a 1000x1000 table of 4-byte ints. You can drop the table, never the index.
The failure this invites is specific: collapse the table and then walk it in an order that reads a cell after it has been overwritten. In 0/1 knapsack the capacity loop must go downward, or every item becomes usable infinitely often; edit distance needs one saved scalar for the diagonal before it is clobbered. Both bugs pass the sample input and surface only on data that reuses an item.
In practice: name the state in words, write the base cases, then pick storage and say the overwrite order out loud. Rolling is correct only while the transition reads a bounded number of earlier rows.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.