Dynamic Programming Explained: Memoization and Tabulation
Dynamic programming (DP) has an intimidating name for a simple idea: when a recursive solution keeps solving the same subproblems, solve each one once, store the answer, and reuse it. That single change can turn an exponential-time algorithm into a polynomial-time one. This guide shows the idea on Fibonacci numbers, gives the two ways to write DP (top-down with memoization, bottom-up with a table), lays out five steps for designing a DP solution, and applies them to counting paths in a grid.
You should be comfortable with recursion first; recursion explained covers base cases and the call stack. Examples use Python 3.10 or later and only the standard library.
The problem with naive recursion
The Fibonacci numbers are defined by fib(0) = 0, fib(1) = 1 and fib(n) = fib(n - 1) + fib(n - 2). That definition translates directly into a recursive function, and the program below counts how many calls it makes, then solves the same problem two better ways:
from functools import cache
calls = 0
def fib_naive(n):
global calls
calls += 1
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
memo_calls = 0
@cache
def fib_memo(n):
global memo_calls
memo_calls += 1
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
def fib_table(n):
prev, cur = 0, 1 # fib(0), fib(1)
for _ in range(n):
prev, cur = cur, prev + cur
return prev
print("naive:", fib_naive(20), "calls:", calls)
print("memo: ", fib_memo(20), "calls:", memo_calls)
print("table:", fib_table(20))
naive: 6765 calls: 21891
memo: 6765 calls: 21
table: 6765
The naive version makes 21,891 calls to compute fib(20). The reason is visible if you draw the calls as a tree: fib(20) calls fib(19) and fib(18), but fib(19) calls fib(18) again, and each of those calls fib(17), and so on. fib(18) is computed twice, fib(17) three times, fib(16) five times; the repetition itself follows the Fibonacci numbers. The total number of calls is 2 x fib(n + 1) - 1, which grows exponentially: roughly by a factor of 1.618 for each increase of n by one. O(2^n) is a valid, if loose, upper bound for it.
To feel what exponential means, the Big O Complexity Analyzer evaluates 2^n at n = 20 as 1,048,576, against 20 for n. Naive Fibonacci grows a bit slower than 2^n, but it is in the same family: each step up in n multiplies the work instead of adding to it.
The two DP ingredients
Dynamic programming applies when a problem has two properties.
- Overlapping subproblems: the same smaller problems come up again and again. fib(18) is needed by both fib(20) and fib(19). (Merge sort, by contrast, splits into halves that never overlap, so storing answers would not help; it is plain divide and conquer.)
- Optimal substructure: the answer to a problem can be built from the answers to its subproblems. For Fibonacci this is just the recurrence; for optimization problems it means an optimal solution contains optimal solutions to its parts.
Top-down: memoization
Memoization keeps the recursive code and adds a cache: before computing fib(n), check whether it has been computed already. In Python, the decorator functools.cache does that for you (it is the same as functools.lru_cache(maxsize=None); see the functools documentation). The arguments must be hashable, which integers are.
In the run above, the memoized version makes 21 calls for fib(20): one for each value from 0 to 20. Every later request is answered from the cache. The time is O(n): n + 1 states, constant work each. The space is O(n) for the cache plus O(n) recursion depth, and that depth matters in Python: with the default recursion limit of 1000, a memoized call for a large n can still raise RecursionError.
Bottom-up: tabulation
Tabulation turns the recursion around. Start from the base cases and fill in answers in an order where everything a value needs has already been computed. For Fibonacci, that order is simply 0, 1, 2, and so on, and since each value needs only the previous two, the "table" can shrink to two variables. fib_table runs in O(n) time and O(1) space, with no recursion at all.
| Version | Time | Extra space | Calls for fib(20) |
|---|---|---|---|
| Naive recursion | Exponential | O(n) stack | 21,891 |
| Memoized (top-down) | O(n) | O(n) cache + O(n) stack | 21 |
| Tabulated, two variables (bottom-up) | O(n) | O(1) | 1 (no recursion) |
Which should you write? Memoization is often quicker to get right, because it is the recursive definition plus one decorator, and it only computes the states that are actually needed. Tabulation avoids recursion limits and function-call overhead, and it makes space savings like the two-variable trick easy to see. Both have the same time bound.
Five steps for a DP solution
- Define the state. Say in one sentence what a subproblem is and what number you store for it: "paths(r, c) is the number of ways to reach cell (r, c)."
- Write the recurrence. Express a state in terms of smaller states.
- Set the base cases. The states you can answer directly, without the recurrence.
- Choose an order. For tabulation, an order in which every state's dependencies come first. (Memoization finds the order for you.)
- Read off the answer. Usually one particular state, sometimes the minimum or maximum over several.
Worked example: paths through a grid
In an m by n grid you start at the top-left cell and may move only right or down. How many different paths reach the bottom-right cell?
- State: paths(r, c) is the number of ways to reach row r, column c (counting from 0).
- Recurrence: the last move into (r, c) came from above or from the left, so paths(r, c) = paths(r - 1, c) + paths(r, c - 1).
- Base cases: every cell in the top row or the left column has exactly one path (go straight).
- Order: row by row, left to right, so the cell above and the cell to the left are always done.
- Answer: paths(m - 1, n - 1).
from functools import cache
from math import comb
def grid_paths_memo(m, n):
@cache
def paths(r, c): # ways to reach (r, c) from (0, 0)
if r == 0 or c == 0:
return 1
return paths(r - 1, c) + paths(r, c - 1)
return paths(m - 1, n - 1)
def grid_paths_table(m, n):
row = [1] * n # first row: one way to each cell
for _ in range(1, m):
for c in range(1, n):
row[c] += row[c - 1] # from above (old row[c]) + from the left
return row[-1]
print(grid_paths_memo(3, 7), grid_paths_table(3, 7), comb(3 + 7 - 2, 2))
print(grid_paths_memo(18, 18), grid_paths_table(18, 18), comb(34, 17))
28 28 28
2333606220 2333606220 2333606220
Both versions agree, and both match the closed-form check from math.comb: a path is m - 1 down moves and n - 1 right moves in some order, and there are C(m + n - 2, m - 1) ways to arrange them. A 3 by 7 grid has 28 paths; an 18 by 18 grid has 2,333,606,220, far too many to list one by one, yet the table fills 324 cells.
The memoized version has m x n states and does constant work per state, so it runs in O(mn) time with O(mn) cache space. The tabulated version keeps a single row: when it updates row[c], the old value is the cell above and row[c - 1] is already the cell to the left. It also takes O(mn) time but only O(n) space. That "states times work per state" count is the general rule for DP running time, worked through on harder problems in dynamic programming time complexity.
Common mistakes
- A state that leaves something out. If the answer depends on something the state does not record (which items are still available, the remaining capacity), the cached values are wrong. Ask: does knowing only these arguments determine the answer?
- Caching a function with side effects, or one that reads a global that changes between calls.
- Wrong fill order in tabulation: reading a cell before it has been written.
- Memoizing on mutable arguments:
functools.cacheraisesTypeErrorfor a list argument. Pass indexes or tuples instead.
Check yourself
- How many distinct states does memoized fib(50) compute? (51, for 0 to 50.)
- Count the paths in a 2 by 3 grid by hand, then with the formula. (3; C(3, 1) = 3.)
- Why is merge sort not usually called DP? (Its subproblems do not overlap, so there is nothing to reuse.)