Sub topic 12
Shrinking the table: rolling arrays and variables
This chapter assumes you can write the tabulated Fibonacci and longest common subsequence (LCS) solutions from earlier chapters. You should also be able to read time and space complexity as the number of states times the work per state.
A full DP table stores every state. Many recurrences only read a few recent entries, though. When that is true, you can throw away the older entries and keep the cost in memory proportional to what the recurrence actually reads.
Find what the recurrence reads
Before you shrink a table, write down which earlier states each entry depends on.
| Problem | Recurrence reads | Full table | Shrunk storage |
|---|---|---|---|
| Fibonacci | `dp[i-1]`, `dp[i-2]` | O(n) | O(1), two variables |
| LCS length | row `i-1` and the current row | O(m·n) | O(n), two rows |
| Coin change | any `dp[a-c]` for coin `c` | O(amount) | no saving, already 1D |
Coin change stays as it is because dp[a - c] can reach far back. Keep every entry that a future step might still read.
From a list to two variables
In tabulated Fibonacci, table[i] uses only table[i-1] and table[i-2]. Two variables can hold both:
def fib(n):
prev, curr = 0, 1
for _ in range(n):
prev, curr = curr, prev + curr
return prev
print([fib(i) for i in range(10)]) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]The tuple assignment matters here. Python evaluates curr, prev + curr before it assigns anything, so the new curr is computed from the old prev. If you wrote prev = curr and then curr = prev + curr as two separate lines, curr would be doubled instead of advanced.
Rolling rows in a 2D table
In LCS, cell dp[i][j] reads dp[i-1][j-1], dp[i-1][j], and dp[i][j-1]. Those cells sit in the previous row or earlier in the current row. So you only need two rows at a time: prev and curr.
def lcs_length(a, b):
if len(a) < len(b):
a, b = b, a # LCS is symmetric; make the row as short as possible
n = len(b)
prev = [0] * (n + 1)
for i in range(1, len(a) + 1):
curr = [0] * (n + 1)
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
curr[j] = prev[j - 1] + 1
else:
curr[j] = max(prev[j], curr[j - 1])
prev = curr
return prev[n]
print(lcs_length("ABCBDAB", "BDCABA")) # 4Memory drops from O(m·n) to O(min(m, n)), and time stays O(m·n). Swapping the strings so the shorter one sets the row width gives the extra saving for free.
You can go down to a single row if you save the diagonal value prev[j-1] in a temporary variable before you overwrite it. That saves one row but makes the code harder to read. Use it only when memory is very tight.
Common errors
- Overwriting a value you still need. When one array plays both "old" and "new", the loop direction decides which value you read. The next chapter's 0/1 knapsack loops capacity downward for exactly this reason.
- Aliasing rows. Writing
prev = currand then changingcurrin place changesprevtoo. Either create a freshcurron each pass, as shown above, or swap two preallocated lists. - Losing reconstruction. Tracing back from
dp[m][n]needs the whole table. If you need the actual subsequence and not just its length, keep the full table, or use a divide-and-conquer method such as Hirschberg's algorithm.
Exercise
In the grid-paths problem, paths[i][j] = paths[i-1][j] + paths[i][j-1], where every cell in row 0 and column 0 equals 1. Write a version that uses a single 1D list for an r-by-c grid, and say which direction the inner loop must run.
Show answer
Use row = [1] * c. Then for each of the remaining r-1 rows, run for j in range(1, c): row[j] += row[j-1], and return row[c-1]. The loop must run left to right. Before you update it, row[j] still holds the value from the row above. row[j-1] has already been updated for the current row, which is the value the recurrence needs.
Exercise
Why does the two-row LCS function above not let you recover the subsequence itself?
Show answer
The trace-back walks from dp[m][n] through earlier rows to decide each step. The two-row version has already thrown those rows away. Only the final row survives, and that is enough for the length but not for the path.