Sub topic 1
Where DP Memory Goes: States, Transitions, and Tables
Prerequisites
This chapter assumes you know basic dynamic programming (recurrences, memoization, bottom-up tabulation) and Big-O analysis of time and space. You should be comfortable with Python loops and arrays, and with Fibonacci and longest common subsequence (LCS).
States, Transitions, and Table Cost
A DP state is a tuple of parameters, such as i or (i, j), that identifies one subproblem. A transition is the rule that computes a state's value from other states. A full table stores one entry per state, so its memory equals the size of the state space. For Fibonacci that is O(n). For LCS on strings of lengths m and n it is O(m·n).
Most of those entries are needed only briefly. The rest of this tutorial is about finding them and throwing them away.
Reading the Dependency Pattern
Write down exactly which states each transition reads. For LCS, cell (i, j) reads (i-1, j-1), (i-1, j), and (i, j-1). All three sit in the current row or the previous one.
If a transition reaches back at most k layers, you only need to keep k layers in memory.
Constant Space with Rolling Variables
Fibonacci reads only the previous two values, so two variables can replace the O(n) table:
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fib(10)) # 55The tuple assignment updates both variables at once. If you write a = b; b = a + b instead, you get a common bug, because b then reads the new a.
From a Full Table to Two Rows
Row i of the LCS table reads only row i-1 and itself. That means two rows are enough. Swap the strings so the rows are as long as the shorter one, and space drops to O(min(m, n)):
def lcs_length(x, y):
if len(x) < len(y):
x, y = y, x
prev = [0] * (len(y) + 1)
for i in range(1, len(x) + 1):
curr = [0] * (len(y) + 1)
for j in range(1, len(y) + 1):
if x[i - 1] == y[j - 1]:
curr[j] = prev[j - 1] + 1
else:
curr[j] = max(prev[j], curr[j - 1])
prev = curr
return prev[len(y)]
print(lcs_length("ABCBDAB", "BDCABA")) # 4Exercise
A recurrence computes dp[i] from dp[i-1] and dp[i-3]. How many earlier values must you keep, and what is the space complexity?
Show answer
Three values (dp[i-1], dp[i-2], dp[i-3]), because dp[i-2] will be needed as dp[(i+1)-3]. Space is O(1).
Exercise
In lcs_length, why does the code swap x and y when x is shorter?
Show answer
The rows have length len(y) + 1, so making y the shorter string keeps memory at O(min(m, n)).