Sub topic 6
Bottom-up DP with tabulation
Memoization keeps the recursive shape of a recurrence and adds a cache. Tabulation drops the recursion. You allocate a table with one slot per state, write the base cases into it, and then fill the remaining slots in a loop. The loop order guarantees that each value a slot needs is already in the table. The recurrence stays the same. The difference is who decides the order of evaluation: in memoization the call stack decides, and in tabulation you decide.
This chapter assumes you can already define a DP state, write its recurrence, and identify its base cases, as covered in the earlier chapters. You should also be comfortable with Python loops, list indexing, and nested lists.
The idea: fill a table in dependency order
Every recurrence implies a dependency relation: state i depends on the states that appear on the right-hand side of its formula. A bottom-up solution has three parts:
- Allocate a table indexed by the state, large enough to hold every state you will read or write.
- Seed the base cases directly into the table.
- Fill the rest of the table with loops whose order visits every dependency before any state that uses it.
When the loop finishes, the answer sits in the slot for the original problem.
Converting the Fibonacci recurrence
The Fibonacci recurrence is F(i) = F(i-1) + F(i-2) with base cases F(0) = 0 and F(1) = 1. Each state depends on two smaller indices, so filling the table from low indices to high works.
def fib(n):
if n < 2:
return n
table = [0] * (n + 1)
table[1] = 1
for i in range(2, n + 1):
table[i] = table[i - 1] + table[i - 2]
return table[n]
print(fib(6)) # 8
print(fib(50)) # 12586269025Line by line, this maps onto the three parts:
table = [0] * (n + 1)allocates slots for indices0throughn. That isn + 1slots, and the extra one is easy to forget.table[1] = 1seeds the second base case. The first one,table[0] = 0, is already correct because the table starts at zero.- The
forloop starts at2, the first index that is not a base case, and runs throughninclusive.
Here is the table after fib(6) finishes:
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| table[i] | 0 | 1 | 1 | 2 | 3 | 5 | 8 |
Each entry is written once and read at most twice. Nothing is recomputed and no function calls itself.
The guard if n < 2: return n matters. Without it, fib(0) would allocate a table of length 1 and then fail on table[1] = 1 with an IndexError. Small inputs where the table is shorter than the base cases are a common edge case in tabulated code.
Valid fill orders
A fill order is valid when, at the moment you compute any state, every state it reads has already been written. Think of the states as nodes in a directed graph with an edge from each dependency to the state that uses it. A valid fill order is a topological order of that graph.
For Fibonacci all edges point toward larger indices, so the obvious increasing loop is valid. That is not always true. You have to read the order off the recurrence each time.
When the loop must run backward
Suppose the state is "number of ways to reach the top step n starting from step i, climbing 1 or 2 steps at a time." The recurrence is ways[i] = ways[i+1] + ways[i+2], with base case ways[n] = 1. Here each state depends on larger indices, so the loop has to run from high to low.
def ways_to_top(n):
# Slot n + 1 is a sentinel: overshooting the top contributes 0 ways.
ways = [0] * (n + 2)
ways[n] = 1
for i in range(n - 1, -1, -1):
ways[i] = ways[i + 1] + ways[i + 2]
return ways[0]
print(ways_to_top(3)) # 3 (1+1+1, 1+2, 2+1)
print(ways_to_top(0)) # 1 (already at the top)The extra sentinel slot at n + 1 lets the loop body apply the same formula at i = n - 1 without a special case. Padding a table with neutral boundary values is a standard way to keep loop bodies uniform.
Here is the same body with a forward loop:
def ways_to_top_wrong(n):
ways = [0] * (n + 2)
ways[n] = 1
for i in range(0, n): # wrong direction
ways[i] = ways[i + 1] + ways[i + 2]
return ways[0]
print(ways_to_top_wrong(3)) # 0, not 3Python does not raise an error here. The loop reads slots that still hold their initial zeros and quietly produces a wrong answer. This is the most dangerous tabulation bug because nothing visibly fails.
Fill order in two dimensions
With two state variables you choose the order of two nested loops. Take the problem of counting paths from the top-left to the bottom-right of a grid. You may move only right or down, and cells marked 1 are blocked. The recurrence is dp[r][c] = dp[r-1][c] + dp[r][c-1] for open cells and 0 for blocked cells.
def grid_paths(grid):
rows, cols = len(grid), len(grid[0])
dp = [[0] * cols for _ in range(rows)]
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
dp[r][c] = 0
continue
if r == 0 and c == 0:
dp[r][c] = 1
continue
from_top = dp[r - 1][c] if r > 0 else 0
from_left = dp[r][c - 1] if c > 0 else 0
dp[r][c] = from_top + from_left
return dp[rows - 1][cols - 1]
grid = [
[0, 0, 0],
[0, 1, 0],
[0, 0, 0],
]
print(grid_paths(grid)) # 2Row-major order, which visits every column of row 0 and then every column of row 1, is valid. The cell above belongs to an earlier row, and the cell to the left comes earlier in the current row. Column-major order would also be valid for this recurrence, because both dependencies still come first. A recurrence that reads dp[r-1][c+1] (up and to the right) also works in row-major order, but not in column-major order, because column c+1 would not have been filled yet. Check every dependency offset against the loop nesting whenever you change the order.
Sizing the table and seeding base cases
Most tabulation bugs come from setup rather than from the recurrence. The following choices come up often:
| Decision | Typical choice | Why |
|---|---|---|
| Table length for states `0..n` | `n + 1` | Includes both endpoints |
| Boundary handling | Extra padding row, column, or sentinel slot | Removes `if` checks from the loop body |
| Initial value for a minimization | `float('inf')` | Any real candidate replaces it |
| Initial value for a maximization or count | `0` (or `-inf` if 0 is a real value) | Neutral element for `max` or `+` |
| Where the answer lives | Slot for the original problem, e.g. `table[n]` or `ways[0]` | Depends on the fill direction |
The answer is not always in the last slot filled. In ways_to_top the loop finishes at index 0, and the answer is there because state 0 is the original question, not because it was filled last.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Wrong answer, no exception | Loop reads slots not yet filled | Reverse or reorder loops to match dependencies |
| `IndexError` on small inputs | Base-case seeding writes past a short table | Guard small `n` or pad the table |
| Off by one in the result | Table of size `n` instead of `n + 1`, or `range(2, n)` instead of `range(2, n + 1)` | Write the state range down explicitly before coding |
| Every row changes together | Rows created with `[[0] * cols] * rows` share one list | Use a list comprehension |
| Answer is `inf` or `-inf` | Target state unreachable from the base cases | Detect the sentinel and return a defined "no solution" value |
The shared-row bug deserves a demonstration, because it produces convincing but wrong tables:
bad = [[0] * 3] * 2
bad[0][0] = 5
print(bad) # [[5, 0, 0], [5, 0, 0]] both rows are the same list
good = [[0] * 3 for _ in range(2)]
good[0][0] = 5
print(good) # [[5, 0, 0], [0, 0, 0]][0] * 3 is safe because integers are immutable. Multiplying the outer list copies references to one inner list, so a write through any row changes all of them.
What changes compared with memoization
The recurrence, the states, and the base cases do not change. What changes is how they are evaluated:
- No recursion depth limit. CPython's default recursion limit is about 1000 frames, so a memoized
fib(5000)raisesRecursionErrorunless you raise the limit. The tabulated version runs with a constant-depth call stack. - Every state in the loop range is computed, including states the original problem never needs. For Fibonacci all states are needed, but in some problems this is wasted work.
- The memory layout is explicit. Because you can see exactly which slots each step reads, the table is easier to shrink later, as a later chapter shows.
The later chapters on complexity and on choosing between the two styles weigh these trade-offs in detail.
Checking a table against the memoized version
A memoized implementation is usually easier to get right, because it follows the recurrence directly and needs no fill order. That makes it a good reference for testing a tabulated version on many small inputs:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
def fib_tab(n):
if n < 2:
return n
table = [0] * (n + 1)
table[1] = 1
for i in range(2, n + 1):
table[i] = table[i - 1] + table[i - 2]
return table[n]
assert all(fib_tab(n) == fib_memo(n) for n in range(300))
print("tabulation matches memoization for n in 0..299")Make sure the test range includes the base cases and the smallest non-base inputs. Those inputs are where the sizing and seeding bugs show up.
Exercise
A recurrence is defined by dp[i] = dp[i + 1] + 2 * dp[i + 3] for 0 <= i < n, with dp[n] = 1 and every dp[k] = 0 for k > n. Write a tabulated Python function that returns dp[0], and state the fill direction and the table size you need.
Show answer
Each state depends on larger indices, so fill from i = n - 1 down to 0. Indices up to n + 2 can be read, so allocate n + 3 slots with zeros as sentinels: def f(n): dp = [0] (n + 3); dp[n] = 1; then for i in range(n - 1, -1, -1): dp[i] = dp[i + 1] + 2 dp[i + 3]; return dp[0]. For n = 3 this gives dp[2] = 1, dp[1] = 1, dp[0] = 1 + 2 * 1 = 3.
Exercise
In grid_paths, suppose the recurrence also allowed a diagonal move from the up-right cell, so dp[r][c] also adds dp[r - 1][c + 1]. Is row-major order still valid? Is column-major order (outer loop over c, inner loop over r) valid?
Show answer
Row-major order is still valid, because row r - 1 is fully filled before row r begins, which includes column c + 1. Column-major order is not valid, because when you compute column c, column c + 1 has not been filled yet, so dp[r - 1][c + 1] still holds its initial 0.
Exercise
A student writes dp = [[float('inf')] (cols + 1)] (rows + 1) for a minimization table and finds that setting dp[0][0] = 0 makes the whole first column 0. Explain why and give the fix.
Show answer
Multiplying the outer list repeats a reference to the same inner list, so every row is one shared list and writing dp[0][0] changes index 0 of every row. Build independent rows with dp = [[float('inf')] * (cols + 1) for _ in range(rows + 1)].