Memoization vs Tabulation
Two ways to run the same DP recurrence. Memoization starts from the question and recurses, caching each answer. Tabulation starts from the base cases and fills a table in order. The answers match; the work, memory and failure modes do not.
One Recurrence, Two Orders
A DP problem is a recurrence: the answer for a state is built from answers for smaller states. Memoization vs tabulation is a choice about how to evaluate that recurrence, not about what it says. Memoization writes it as a recursive function and stores each result the first time it is computed, so a repeated call becomes a lookup. Tabulation writes it as a loop that fills a table from the base cases upward, in an order where everything a state needs is already filled.
That is why the two are also called top-down and bottom-up. Top-down starts at the state you were asked about and works toward the base cases; the recursion decides the order. Bottom-up starts at the base cases and works toward the answer; you decide the order. The tracer below runs both on one recurrence and counts what each one does.
- Both rely on the same two properties described in dynamic programming: subproblems repeat, and an answer is built from answers to smaller ones
- If they give different answers, one of them has a bug; the recurrence is the same
Top Down vs Bottom Up Dynamic Programming
The practical difference between memoization and tabulation shows up in four places: which states get computed, how deep the call stack goes, whether you must plan the fill order, and whether old results can be thrown away. The table sums it up; the next two sections explain when each side matters.
| Memoization (top-down) | Tabulation (bottom-up) | |
|---|---|---|
| Shape of the code | Recursive function + cache | Loops + array |
| States computed | Only those reachable from the question | Every state in the table |
| Call stack | As deep as the longest chain | None |
| Fill order | Found automatically by recursion | Must be worked out by hand |
| Dropping old rows | Not possible | Often possible (rolling array) |
| Overhead per state | Function call, often a hash lookup | One array access |
- Time is the same, O(states × work per state), when every state is needed
- Memoization's memory is the cache plus the stack; tabulation's is the table, sometimes much less after rolling
When Memoization Wins
Memoization wins when the question only reaches a small part of the state space. In the tracer's coin problem, best(k) needs best(k/2), best(k/3) and best(k/4). From 12 that reaches 7 of the 13 states. From one billion it reaches 242 states, while a table would need a billion and one cells. Any recurrence that jumps by division, or whose valid states are scattered, has this shape.
It also wins when the fill order is awkward. For states on a tree, a DAG, a set of chosen items or an (index, remaining) pair with many invalid combinations, working out a safe loop order takes thought, and a recursive function with a cache simply follows the dependencies. That makes top-down the faster way to get a first correct solution.
- Sparse reachable states: memoization does less work
- Hard-to-order states: recursion finds the order for you
- Writing it is usually a two-line change to the plain recursive solution
Terms, operations, and practical uses
Key terms
- Top-downStart from the question, recurse to the base cases, cache on the way back.
- Bottom-upStart from the base cases and fill states in dependency order with loops.
- Reachable statesThe states a recursion actually visits from the question; can be far fewer than the full table.
- Rolling arrayKeeping only the last row or two of a table because nothing older is read.
Related lessons and problems
- MemoizationCache keys, eviction and the top-down technique in depth.
- Dynamic ProgrammingThe two conditions and the tabulation method.
- One-Dimensional Dynamic ProgrammingRolling variables in practice.
- Climbing Stairs (problem)The deep chain from the tracer's last step.
- Fibonacci Number (problem)Write it both ways and compare.
Code in Python, C++ and Java
def exchange_memo(n):
cache = {}
deepest = [0]
def best(k, depth):
deepest[0] = max(deepest[0], depth)
if k == 0:
return 0
if k not in cache:
cache[k] = max(k, best(k // 2, depth + 1) + best(k // 3, depth + 1) + best(k // 4, depth + 1))
return cache[k]
answer = best(n, 1)
return answer, len(cache) + 1, deepest[0]
def exchange_table(n):
dp = [0] * (n + 1)
for k in range(1, n + 1):
dp[k] = max(k, dp[k // 2] + dp[k // 3] + dp[k // 4])
return dp[n], n + 1
def stairs_table(n, mod=1_000_000_007):
one_back, two_back = 1, 1
for _ in range(2, n + 1):
one_back, two_back = (one_back + two_back) % mod, one_back
return one_back
for n in (12, 1000):
answer, states, depth = exchange_memo(n)
table_answer, cells = exchange_table(n)
print(f"n = {n}: memo {answer} from {states} states, table {table_answer} from {cells} cells")
answer, states, depth = exchange_memo(1_000_000_000)
print(f"n = 1000000000: memo {answer} from {states} states, recursion depth {depth}")
print("stairs n = 100000 by table:", stairs_table(100_000), "(memo would recurse 100000 deep)")#include <algorithm>
#include <cstdio>
#include <unordered_map>
#include <vector>
using namespace std;
unordered_map<long long, long long> cache;
int deepest = 0;
long long best(long long k, int depth) {
deepest = max(deepest, depth);
if (k == 0) return 0;
auto it = cache.find(k);
if (it != cache.end()) return it->second;
long long split = best(k / 2, depth + 1) + best(k / 3, depth + 1) + best(k / 4, depth + 1);
return cache[k] = max(k, split);
}
long long exchangeTable(int n) {
vector<long long> dp(n + 1, 0);
for (int k = 1; k <= n; k++) dp[k] = max((long long)k, dp[k / 2] + dp[k / 3] + dp[k / 4]);
return dp[n];
}
long long stairsTable(int n) {
const long long MOD = 1000000007;
long long oneBack = 1, twoBack = 1;
for (int i = 2; i <= n; i++) {
long long next = (oneBack + twoBack) % MOD;
twoBack = oneBack;
oneBack = next;
}
return oneBack;
}
int main() {
for (int n : {12, 1000}) {
cache.clear(); deepest = 0;
long long answer = best(n, 1);
printf("n = %d: memo %lld from %zu states, table %lld from %d cells\n",
n, answer, cache.size() + 1, exchangeTable(n), n + 1);
}
cache.clear(); deepest = 0;
long long answer = best(1000000000LL, 1);
printf("n = 1000000000: memo %lld from %zu states, recursion depth %d\n", answer, cache.size() + 1, deepest);
printf("stairs n = 100000 by table: %lld (memo would recurse 100000 deep)\n", stairsTable(100000));
}import java.util.HashMap;
import java.util.Map;
public class Main {
static Map<Long, Long> cache = new HashMap<>();
static int deepest = 0;
static long best(long k, int depth) {
deepest = Math.max(deepest, depth);
if (k == 0) return 0;
Long known = cache.get(k);
if (known != null) return known;
long split = best(k / 2, depth + 1) + best(k / 3, depth + 1) + best(k / 4, depth + 1);
long value = Math.max(k, split);
cache.put(k, value);
return value;
}
static long exchangeTable(int n) {
long[] dp = new long[n + 1];
for (int k = 1; k <= n; k++) dp[k] = Math.max(k, dp[k / 2] + dp[k / 3] + dp[k / 4]);
return dp[n];
}
static long stairsTable(int n) {
final long MOD = 1_000_000_007L;
long oneBack = 1, twoBack = 1;
for (int i = 2; i <= n; i++) {
long next = (oneBack + twoBack) % MOD;
twoBack = oneBack;
oneBack = next;
}
return oneBack;
}
public static void main(String[] args) {
for (int n : new int[] {12, 1000}) {
cache.clear(); deepest = 0;
long answer = best(n, 1);
System.out.println("n = " + n + ": memo " + answer + " from " + (cache.size() + 1)
+ " states, table " + exchangeTable(n) + " from " + (n + 1) + " cells");
}
cache.clear(); deepest = 0;
long answer = best(1_000_000_000L, 1);
System.out.println("n = 1000000000: memo " + answer + " from " + (cache.size() + 1) + " states, recursion depth " + deepest);
System.out.println("stairs n = 100000 by table: " + stairsTable(100000) + " (memo would recurse 100000 deep)");
}
}Step through it
Running on best(k) = max(k, best(k/2) + best(k/3) + best(k/4)), n = 12
When Tabulation Wins
Tabulation wins when every state is needed anyway and the dependencies form a long chain. Counting ways to climb n stairs needs every value from 0 to n, and memoized it nests n calls. At n = 100,000 Python stops with RecursionError (its default limit is 1,000), and C++ or Java may crash with a stack overflow. The loop version needs no stack at all.
Tabulation is also the only form that can forget. When row i only reads row i − 1, the table can shrink to one or two rows, as in 0/1 knapsack and one-dimensional DP. A cache cannot do that, because the recursion may ask for any earlier state at any time. Finally, a tight loop over an array avoids per-call overhead and is friendlier to the CPU cache, which can make it several times faster in practice.
- Dense, deep chains: no recursion limit to hit
- Memory matters: roll the table down to a row
- Speed matters: array access beats function calls and hashing
Converting Between the Two
- List the parameters of the recursive function; they are the table's dimensions
- Turn each base case into an initial value in the table
- Look at which smaller states each call uses, and loop in the order that fills those first
- Replace every recursive call with a table lookup
- Read the answer from the cell for the original question
Most people find the memoized version first, because it is the brute-force recursion plus a cache. Turning it into a table is mechanical once you can name the states and see which way the dependencies point.
- Going the other way: wrap the loop body in a function of the state and call it from the answer cell
- If a state's dependencies can point in both directions, there is no valid loop order; keep memoization or rethink the state