Sub topic 3
Constant Space with Rolling Variables
This chapter assumes you can write a bottom-up DP table and state its time and space in Big-O terms. It also assumes you have read the previous chapter on dependency analysis, which covered finding which earlier states a transition reads. Here we use that analysis on the simplest case: a one-dimensional recurrence that looks back only a fixed, small number of steps. When that holds, you can throw away the whole table and keep only a few variables.
The starting point: a full table
The table version of Fibonacci stores every value from F(0) to F(n):
def fib_table(n):
if n == 0:
return 0
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
print(fib_table(10)) # 55This takes O(n) time and O(n) space. Now look at what the transition reads. dp[i] uses dp[i - 1] and dp[i - 2] and nothing else. Once dp[i] exists, dp[i - 2] is never read again. Every entry older than two steps back is dead memory.
The dependency window
The dependency window is the set of earlier states that the transition at step i can read. For Fibonacci it is {i - 1, i - 2}, so its width is 2. The width does not depend on i or n. That fixed width is the condition that makes rolling variables work.
If the window has width k, you need k variables. Each iteration computes the new value from those k variables, then shifts them all one position forward.
Fibonacci in O(1) space
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print([fib(i) for i in range(10)]) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]The loop keeps this invariant, a statement that is true at the start of every iteration: after k iterations, a == F(k) and b == F(k + 1). Before the loop, k = 0, so a = F(0) = 0 and b = F(1) = 1. After n iterations, a == F(n), which is why the function returns a and not b.
Here is a trace for n = 6:
| Iterations done | a | b |
|---|---|---|
| 0 | 0 | 1 |
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 3 |
| 4 | 3 | 5 |
| 5 | 5 | 8 |
| 6 | 8 | 13 |
The result is a = 8 = F(6). The invariant also covers edge cases with no special code. For n = 0 the loop body never runs, so the function returns 0.
The most common bug: update order
Python's tuple assignment a, b = b, a + b evaluates the whole right-hand side before it assigns anything. If you split it into two statements, the second one reads a value you have already overwritten:
def fib_wrong(n):
a, b = 0, 1
for _ in range(n):
a = b
b = a + b # a is already the new value, so this computes 2 * b
return a
print(fib_wrong(5)) # 16, but F(5) is 5After a = b, the old F(i - 2) is gone, and b = a + b doubles b. In languages without simultaneous assignment, or when the update is too complex for one line, compute the new value into a temporary variable first and only then shift:
def fib_temp(n):
a, b = 0, 1
for _ in range(n):
nxt = a + b # read every old value first
a = b # then shift, oldest first
b = nxt
return a
print(fib_temp(5)) # 5The rule is: read every value in the window before you write to any of them, and shift from the oldest slot toward the newest.
A general recipe
- Write the full-table recurrence and check that it is correct.
- List the indices the transition reads. Confirm they are all of the form
i - cfor constantsc, with the largestcequal to k. - Create k variables named for their role, such as
prev2andprev1, and set them to the base cases. - In the loop, compute the new value from the variables, then shift. Use tuple assignment or a temporary.
- Work out which variable holds the answer when the loop ends, using the invariant.
- Test the new version against the table version on small inputs, including the base cases.
More examples
House robber
You cannot rob two adjacent houses. The table recurrence is dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]), and its window width is 2:
def rob(nums):
prev2, prev1 = 0, 0 # best total up to two houses back, and up to one house back
for x in nums:
prev2, prev1 = prev1, max(prev1, prev2 + x)
return prev1
print(rob([2, 7, 9, 3, 1])) # 12 (2 + 9 + 1)
print(rob([])) # 0Starting both variables at 0 stands for "no houses yet". This removes the special cases for empty and single-element inputs.
Min cost climbing stairs
You may start on step 0 or step 1, and each step i costs cost[i] to leave. With dp[i] as the minimum cost to reach step i, the recurrence is dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]):
def min_cost_climb(cost):
a, b = 0, 0 # a = dp[i - 2], b = dp[i - 1]; reaching step 0 or 1 is free
for i in range(2, len(cost) + 1):
a, b = b, min(b + cost[i - 1], a + cost[i - 2])
return b
print(min_cost_climb([10, 15, 20])) # 15
print(min_cost_climb([1, 100, 1, 1, 1, 100, 1, 1, 100, 1])) # 6This recurrence reads from the input array as well as from the window. That is fine, because the input is already in memory. Only the DP state needs to fit in the variables.
Window width 1: running maximum subarray
Kadane's algorithm is a rolling-variable DP with a window of width 1. best_end[i] = max(x, best_end[i - 1] + x), so a single variable cur replaces the table. A second variable tracks the overall best:
def max_subarray(nums):
cur = best = nums[0]
for x in nums[1:]:
cur = max(x, cur + x)
best = max(best, cur)
return best
print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6The variable best is not part of the window. It is a running summary of states you have already thrown away. Many rolling DPs need one of these, because the answer is a max or min over all states rather than the last state.
What "O(1) space" really means
The claim counts machine words. In Python, integers have arbitrary precision, and F(n) has about 0.694 * n bits. So fib(10**6) holds numbers of around 87 KB each, and every addition costs time proportional to their length. If the problem asks for the answer modulo some M, apply % M inside the update. Then every number stays word-sized:
def fib_mod(n, m=10**9 + 7):
a, b = 0, 1
for _ in range(n):
a, b = b, (a + b) % m
return a
print(fib_mod(1000)) # 517691607When rolling variables do not apply
| Situation | Why it fails | What to use instead |
|---|---|---|
| Transition reads `dp[j]` for all `j < i`, as in longest increasing subsequence | The window grows with `i` | Keep the table, or change the formulation |
| Transition reads `dp[i // 2]` or another index that is not a fixed offset | The needed values are not the most recent ones | Memoization or the full table |
| You must answer many queries for different `n` | Discarded values are needed later | Keep the table and reuse it |
| You need the choices that produced the optimum, not only its value | The decisions are thrown away with the states | See the reconstruction chapter later in this tutorial |
| Window width k is large or set at runtime | Naming k variables by hand stops being practical | A circular buffer, covered in the modulo indexing chapter |
Exercises
Exercise
You can climb a staircase by taking 1 or 3 steps at a time. Write a constant-space function ways(n) that returns the number of distinct ways to reach step n, where ways(0) = 1 and negative steps have 0 ways.
Show answer
The recurrence is W(i) = W(i-1) + W(i-3), with a window width of 3, so three variables are needed. One solution: def ways(n): a, b, c = 0, 0, 1 (holding W(i-3), W(i-2), W(i-1) before computing W(1), where W(-2) = W(-1) = 0 and W(0) = 1); then for _ in range(n): a, b, c = b, c, c + a; return c. Checks: ways(0) = 1, ways(3) = 2, ways(4) = 3, ways(5) = 4.
Exercise
In fib, the loop runs n times and the function returns a. If you changed it to return b, what would fib(n) compute, and what would you need to change to return b correctly?
Show answer
By the invariant, after n iterations b == F(n + 1), so returning b gives the next Fibonacci number. To return b correctly, run the loop n - 1 times instead (for n >= 1) and handle n == 0 separately, or start with a, b = 1, 0, which stands for F(-1) = 1 and F(0) = 0, and keep n iterations.
Exercise
A recurrence is defined as dp[i] = dp[i - 1] + dp[i - 4] for i >= 4. A colleague replaces the table with two variables, prev1 and prev4. Why is this wrong, and how many variables are needed?
Show answer
Each step shifts the window by one position. After the shift, the value that must become the new dp[i - 4] is the old dp[i - 3], which was never stored. All four values dp[i - 1] through dp[i - 4] must be kept, so four variables are needed, even though the recurrence reads only two of them.