Sub topic 7
Keeping the Last k Layers with Modulo Indexing
This chapter assumes you know rolling variables for one-dimensional recurrences and two-row rolling arrays for two-dimensional tables, both covered earlier. It also assumes you can read a recurrence and list which earlier states it depends on. Here we generalize both ideas. When a recurrence looks back a fixed number of steps k, you keep a buffer of k slots and find each value's slot with i % k.
The Problem with Shifting Variables
For Fibonacci, two variables are enough, and you shift them with a, b = b, a + b. That pattern stops working well once the lookback grows. Take a recurrence where dp[i] depends on dp[i-1] through dp[i-k]. Shifting means moving k values along by one slot on every step. That costs O(k) per step and is easy to get wrong when you write it by hand.
A ring buffer avoids the copying. Every index i gets a fixed slot, i % k. When you are about to write dp[i], slot i % k holds dp[i - k]. That is the oldest value in the window, and once the current step has used it, nothing will read it again. You overwrite it in place, and no other value has to move.
Tribonacci: The Basic Pattern
The tribonacci sequence adds the previous three terms: T(i) = T(i-1) + T(i-2) + T(i-3). The lookback is 3, so the buffer has 3 slots.
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(10)])
# [0, 1, 1, 2, 4, 7, 13, 24, 44, 81]This works for two reasons:
- Before step
i, the three slots holdT(i-1),T(i-2), andT(i-3)in some order. Addition does not care about order, so the code adds all three slots. - Python evaluates the right-hand side completely before it assigns. The old
T(i-3)in sloti % 3is read first and replaced afterward.
The final answer sits in slot n % 3, not in a fixed position. Returning t[-1] or t[2] is a common bug.
Sizing the Buffer Correctly
The buffer size follows from the dependency analysis. Find the largest offset d that the recurrence reads, meaning dp[i] reads dp[i - d]. Then:
| Case | Buffer size | Why |
|---|---|---|
| You finish reading `dp[i-d]` before writing `dp[i]` | d | The slot you overwrite holds `dp[i-d]`, which is no longer needed |
| You write `dp[i]` early, or in pieces, while still reading old values | d + 1 | The new value needs its own slot so it doesn't destroy `dp[i-d]` |
| The recurrence skips offsets (reads only `i-1` and `i-d`) | Still d | Modulo indexing keeps the whole window, used or not |
If you are unsure whether you read before you write, use d + 1 slots. The extra slot costs one value of memory and removes the risk.
Sliding Windows: Combining the Buffer with a Running Sum
Suppose you are counting the ways to climb n stairs when each move covers 1 to k steps. The recurrence is dp[i] = dp[i-1] + ... + dp[i-k]. Summing the whole buffer costs O(k) per step. A running window sum brings that down to O(1). The buffer is still needed, because when dp[i-k] leaves the window, you have to know its value to subtract it.
def climb_ways(n, k):
buf = [0] * k
buf[0] = 1 # dp[0] = 1: one way to stand at the bottom
window = 1 # sum of dp[i-k .. i-1] for i = 1
for i in range(1, n + 1):
val = window # dp[i]
window += val - buf[i % k] # add dp[i], drop dp[i-k]
buf[i % k] = val # overwrite dp[i-k] with dp[i]
return buf[n % k]
print(climb_ways(3, 2)) # 3
print(climb_ways(10, 3)) # 274The slots start at zero, so for i < k the slot i % k holds 0. That matches the convention that dp at a negative index is zero, and you don't need any special case for the start-up phase. This is often the quickest way to handle start-up in modulo-indexed code. Pick initial buffer contents that make the out-of-range values act correctly.
The result is O(n) time and O(k) space. The full-table version would take O(n) space, or O(nk) time if it summed each window directly.
Layers in Two Dimensions
The same idea works on whole rows of a table. The two-row trick from earlier is the case k = 2, with rows chosen by i % 2. Some recurrences reach back further. Longest palindromic subsequence (LPS) is a good example when you organize it by substring length. Let L[len][i] be the LPS length of the substring that starts at i and has length len:
- If
s[i] == s[i+len-1], thenL[len][i] = L[len-2][i+1] + 2. - Otherwise,
L[len][i] = max(L[len-1][i], L[len-1][i+1]).
Layer len reads layers len-1 and len-2, so the largest offset is 2. We read the old layers while writing the new one cell by cell, which is the "written in pieces" case from the table. So we keep 3 layers.
def lps_length(s):
n = len(s)
if n == 0:
return 0
layers = [[0] * (n + 1) for _ in range(3)]
for i in range(n):
layers[1][i] = 1 # every length-1 substring
for length in range(2, n + 1):
cur = layers[length % 3]
one = layers[(length - 1) % 3]
two = layers[(length - 2) % 3]
for i in range(n - length + 1):
j = i + length - 1
if s[i] == s[j]:
cur[i] = two[i + 1] + 2
else:
cur[i] = max(one[i], one[i + 1])
return layers[n % 3][0]
print(lps_length("bbbab")) # 4
print(lps_length("character")) # 5 ("carac")Space falls from O(n²) to O(n). Notice that cur still holds stale values from layer length - 3 beyond index n - length. The code never reads them: every index it reads, i + 1 <= n - length + 1, lies inside the valid range of the layers it reads from. When you reuse a layer, check this bound yourself. It's easy to read a stale value by mistake.
Gotchas
Negative modulo in other languages
In Python, -1 % 3 is 2. In C, C++, Java, and JavaScript it is -1, which indexes out of bounds or wraps around in the wrong direction. If you ever compute (i - d) % k in those languages, write ((i - d) % k + k) % k, or index only with non-negative values of i.
The answer is in a rotating slot
Always return buf[n % k] (or layers[n % k]). If the loop never runs, for example when n is smaller than the number of base cases, make sure the base-case layout puts each base value at its own index % k. Tribonacci's [0, 1, 1] works because T(i) sits at slot i for i < 3.
Cost of the modulo
An integer modulo is cheap but not free inside tight loops. Two common alternatives:
- When k is a power of two, use
i & (k - 1). - Keep a separate slot counter and reset it to zero when it reaches k.
In Python, the interpreter's own overhead is much larger than the cost of the modulo, so choose whichever version reads most clearly.
When shifting is still better
When k is 2 or 3, named variables (a, b, c = b, c, a + b + c) are usually clearer and just as fast. Modulo indexing pays off when k is larger, when k is a runtime parameter, or when each layer is a whole array, so that shifting would copy O(width) data every step.
Exercise
The recurrence dp[i] = dp[i-2] + dp[i-7] reads only two earlier values. What is the smallest buffer size that works if you read both values before writing dp[i], and which slot holds dp[i-7] at step i?
Show answer
The size is 7, because the largest offset is 7. With size 7, slot i % 7 holds dp[i-7], the oldest value. You read it (and dp[i-2] from slot (i-2) % 7) and then overwrite that slot with dp[i]. A buffer of size 2 would lose dp[i-7] long before step i needs it.
Exercise
In lps_length, why can't we keep only two layers indexed by length % 2, as in the two-row trick?
Show answer
Layer length reads layer length-2. With length % 2, layer length and layer length-2 share the same slot. Writing cur[i] would overwrite two[i], and later cells that need two[i] or nearby values would read new values instead of old ones. Three layers keep length-1 and length-2 safe while length is being written.
Exercise
Modify climb_ways so that each move covers 1 to k steps, but moves of exactly 2 steps are forbidden (assume k >= 3). Describe what changes in the window update.
Show answer
Now dp[i] is the sum of dp[i-1] through dp[i-k], minus dp[i-2]. Keep the same buffer of size k and the same window sum, and compute val = window - buf[(i - 2) % k] when i >= 2, or val = window otherwise. dp[i-2] is still in the buffer because 2 <= k. Then update the window as before: window += val - buf[i % k], followed by buf[i % k] = val.