Sub topic 3
Constant Space with Rolling Variables
This chapter assumes you can write a bottom-up DP table and read a recurrence's dependency pattern, as covered in the previous chapter. The examples are in Python.
When a Table Is More Than You Need
Many one-dimensional recurrences read only a fixed number of earlier entries. Fibonacci is the standard case: F(i) = F(i-1) + F(i-2). A tabulated version allocates n + 1 slots. Once F(i) is computed, though, F(i-2) is never read again. The live part of the table is always a window of two values.
If the window has a fixed size, you can keep it in that many named variables and drop the table. Space falls from O(n) to O(1), and time stays O(n).
The Rolling Fibonacci
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]At the start of each iteration, a holds F(i) and b holds F(i+1). The tuple assignment advances both by one index. After n iterations, a holds F(n).
The Recipe
- Write the recurrence and list every earlier index it reads, for example
i-1andi-2. - Take the largest offset, k. You need k variables.
- Set the variables from the base cases.
- At each step, compute the new value from the variables, then shift every variable one place toward "newer".
- Return whichever variable holds the target index when the loop ends.
The same recipe applies to House Robber, where best(i) = max(best(i-1), best(i-2) + nums[i]):
def rob(nums):
prev2, prev1 = 0, 0
for x in nums:
prev2, prev1 = prev1, max(prev1, prev2 + x)
return prev1
print(rob([2, 7, 9, 3, 1])) # 12Common Errors
Updating in the wrong order
The most frequent bug is overwriting a value before it is read:
def fib_broken(n):
a, b = 0, 1
for _ in range(n):
a = b
b = a + b # a was already overwritten, so this computes 2 * b
return aPython's tuple assignment evaluates the whole right side before it assigns anything, which avoids the problem. In languages without tuple assignment, use a temporary variable: t = a + b; a = b; b = t;.
Off-by-one in the return value
Check which index each variable holds after the final iteration. Returning b instead of a in fib gives F(n+1). Test with n = 0 and n = 1 to catch this.
Losing the path
Rolling variables keep only values. If you need to know which choices produced the optimum, for example which houses were robbed, the discarded entries were the record of those choices. Reconstruction after compression is covered in a later chapter.
| Approach | Time | Space | Can recover choices directly |
|---|---|---|---|
| Full 1D table | O(n) | O(n) | Yes |
| Rolling variables | O(n) | O(1) | No |
Exercise
The recurrence for counting ways to climb n stairs taking 1 or 2 steps is ways(i) = ways(i-1) + ways(i-2), with ways(0) = 1 and ways(1) = 1. Write a constant-space function climb(n) and give climb(5).
Show answer
def climb(n): a, b = 1, 1; then loop n times with a, b = b, a + b; return a. After each iteration a holds ways(i), so the function returns ways(n). climb(5) = 8.
Exercise
A recurrence reads f(i-1) and f(i-3) but never f(i-2). How many rolling variables do you need, and why?
Show answer
Three. The largest offset is 3, so f(i-3) must still be stored when f(i) is computed, and so must f(i-2), because it becomes f(i-3) in the next step. All three values have to be kept and shifted.