Sub topic 7
Keeping the Last k Layers with Modulo Indexing
This chapter assumes you already know rolling variables from the earlier chapter, and that you can read which earlier states a transition depends on. Rolling variables work well when a recurrence looks back one or two steps. When it looks back k steps, renaming k variables by hand at every iteration gets clumsy and easy to get wrong. A buffer of size k, indexed by i % k, does the same job for any k.
The idea: a ring buffer of layers
Suppose dp[i] reads only dp[i-1], dp[i-2], ..., dp[i-k]. At step i, the value dp[i-k] is the oldest one still needed, and step i is the last step that needs it. So dp[i] can be written into the slot that held dp[i-k]. Because i and i - k are congruent mod k, that slot is i % k.
The buffer then works as a ring. Each new value replaces the oldest one, and the k slots always hold the last k layers, though not in order.
Worked example: Tribonacci
Each Tribonacci number is the sum of the previous three, so k = 3:
def tribonacci(n):
t = [0, 1, 1]
if n < 3:
return t[n]
for i in range(3, n + 1):
t[i % 3] = t[0] + t[1] + t[2]
return t[n % 3]
print([tribonacci(i) for i in range(8)]) # [0, 1, 1, 2, 4, 7, 13, 24]On the right-hand side, the slot t[i % 3] still holds T(i-3). Python evaluates the full sum before it assigns, so the old value is read and then replaced. Space drops from O(n) to O(k), and here k = 3.
A general k: climbing stairs with steps 1 to k
Counting the ways to climb n stairs with steps of size 1 through k gives ways[i] = ways[i-1] + ... + ways[i-k], where ways[0] = 1 and negative indices count as 0:
def climb_ways(n, k):
buf = [0] * k
buf[0] = 1
for i in range(1, n + 1):
buf[i % k] = sum(buf)
return buf[n % k]
print(climb_ways(3, 2)) # 3
print(climb_ways(4, 3)) # 7The same code works for every k. Starting the buffer with zeros stands in for the negative indices.
The same trick for 2D layers
When dp[i][j] reads whole rows i-1 through i-k, keep k rows and use dp[i % k][j]. With k = 2 you get the two-row rolling array from the earlier chapter, so that technique is a special case of this one.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Buffer of size k when the oldest value is read after the write | Wrong values from step k onward | Read everything before writing, or use size k + 1 |
| Accumulating with `+=` into a reused slot or row | Leftover values from layer i - k get added in | Reset the slot or row before you accumulate |
| Returning `buf[-1]` or `buf[k-1]` | Answer from the wrong layer | Return `buf[n % k]` |
| Using `i % k` when the recurrence looks back k + 1 steps | Overwrites a value that is still needed | Set the buffer size to the largest lookback |
Exercise
The recurrence f(i) = f(i-1) + 2*f(i-3) has f(0)=1, f(1)=1, f(2)=1. Write a function using modulo indexing that returns f(n), and state its space usage.
Show answer
Use a buffer of size 3, because the largest lookback is 3: def f(n): b = [1, 1, 1]; then for i in range(3, n + 1): b[i % 3] = b[(i - 1) % 3] + 2 * b[i % 3]; return b[n % 3]. Before the write, b[i % 3] holds f(i-3), so it is read and then replaced. This gives f(3)=3, f(4)=5, f(5)=7, f(6)=13, and the function uses O(1) space, or O(k) in general.