Sub topic 6
Bottom-up DP with tabulation
This chapter assumes you can write Python loops and lists, and that you have seen a DP recurrence with base cases and a memoized solution. Here the same Fibonacci recurrence is solved in the opposite direction: from the base cases up to the answer, with no recursion.
The idea: fill a table in dependency order
Memoization starts at the question you want answered, fib(n), and recurses down until it reaches a base case. Tabulation reverses this. You allocate a table with one slot per state. You write the base cases into it, then fill the remaining slots in an order that guarantees each slot's dependencies are already filled.
For Fibonacci, the state is i, the recurrence is F(i) = F(i-1) + F(i-2), and the base cases are F(0) = 0 and F(1) = 1. Each entry depends only on entries with smaller indices, so increasing i is a valid fill order.
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(i) for i in range(10)]) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
print(fib(500) % 1_000_000_007) # works without hitting recursion limitsTranslating a recurrence into a table
The same four steps apply to any recurrence:
- Size the table so it has one slot per state. For states
0..n, that isn + 1slots. - Write the base cases into their slots.
- Choose a fill order in which every state comes after the states it reads.
- Return the slot for the original question, which is often the last one filled, though not always.
The loop body is the recurrence, written with table[...] lookups in place of recursive calls.
Finding a valid fill order
Draw the dependencies as arrows, as in the diagram above. A valid order is any order where every arrow points from a slot already filled to the slot being filled. For one-dimensional problems where i depends on smaller indices, a plain for i in range(...) loop works.
Two-dimensional states need more thought. If dp[i][j] reads dp[i-1][j], dp[i][j-1], and dp[i-1][j-1], then filling row by row with i increasing and, within each row, j increasing satisfies every dependency. If a recurrence reads dp[i+1][...], you loop i downward instead. Later chapters use both patterns.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Table of size `n` instead of `n + 1` | `IndexError` on `table[n]` | Count states, including state 0 |
| Base case left out of the table | Answers are off by a constant or all zero | Write every base case before the loop |
| Loop starts at the wrong index | Base cases get overwritten, or the loop reads negative indices | Start the loop just after the last base case |
| Fill order disagrees with the dependencies | Wrong answer with no error | Trace which slots each entry reads |
| Small `n` not guarded | `table[1] = 1` fails when `n = 0` | Handle `n < 2` before allocating |
Negative indices are a Python trap of their own. table[-1] is valid Python and returns the last element, so an off-by-one error in the loop start can read garbage silently.
What tabulation gives you
Tabulation uses no recursion, so deep inputs cannot overflow the call stack. A loop over a list also tends to run faster than function calls with cache lookups. The cost is that you fill every state, including ones the answer never needs, and you must work out the fill order yourself. A later chapter covers when that trade-off favors memoization.
Exercise
The Tribonacci sequence is T(0) = 0, T(1) = 0, T(2) = 1, and T(i) = T(i-1) + T(i-2) + T(i-3) for i >= 3. Write a tabulated function trib(n). What are the table size, the base cases, the loop range, and the value of trib(7)?
Show answer
The table has n + 1 slots. The base cases are table[0] = 0, table[1] = 0, and table[2] = 1, and the function returns them directly when n < 3. The loop is for i in range(3, n + 1), computing table[i] = table[i-1] + table[i-2] + table[i-3]. The sequence runs 0, 0, 1, 1, 2, 4, 7, 13, so trib(7) = 13.
Exercise
A recurrence is defined as dp[i] = dp[i + 1] + dp[i + 2] for 0 <= i < n, with base cases dp[n] = 1 and dp[n + 1] = 0. Which loop gives a valid fill order, and which slot holds the answer to the original question dp[0]?
Show answer
Each entry reads larger indices, so the loop must run downward: for i in range(n - 1, -1, -1). The table needs n + 2 slots, and the answer is dp[0], the last slot filled. It is not at the end of the list.