Lesson 3 · Dynamic programming

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.

Memoization vs Tabulation concept diagramLeft: the memoized recursion for ways(5) in climbing stairs. Calls go down a spine 5, 4, 3, 2, 1; each node's second call (3, 2, 1, 0) is answered from the cache, so the tree has no repeated branches but the call stack is five frames deep. Right: tabulation fills ways[0] to ways[5] as 1, 1, 2, 3, 5, 8 from left to right in a loop with no recursion.Memoization: start at ways(5)53cache hit42cache hit31cache hit20base case1base casecall stack: 5 deepTabulation: start at the base cases101122335485ways[i], base cases ways[0] = ways[1] = 1loop i = 2 … 5no recursion, no stackeach cell reads only the two before itsame recurrence ways(n) = ways(n − 1) + ways(n − 2), same answer 8, opposite direction
1

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
2

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.

Top down vs bottom up dynamic programming
Memoization (top-down)Tabulation (bottom-up)
Shape of the codeRecursive function + cacheLoops + array
States computedOnly those reachable from the questionEvery state in the table
Call stackAs deep as the longest chainNone
Fill orderFound automatically by recursionMust be worked out by hand
Dropping old rowsNot possibleOften possible (rolling array)
Overhead per stateFunction call, often a hash lookupOne 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
3

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
Key reference

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.
Implementation

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)");
    }
}
Watch it run

Step through it

Running on best(k) = max(k, best(k/2) + best(k/3) + best(k/4)), n = 12

states k = 0 … 12 · best(k) = max(k, best(k/2) + best(k/3) + best(k/4))0123456789101112call stackemptyBlue = filled by memoization (top-down)Green = filled by tabulation (bottom-up)best(0) = 0 is the only base case.
Step 1

One recurrence, two ways to evaluate it

A coin worth k can be sold for k, or swapped for three coins worth k/2, k/3 and k/4 (rounded down), which can be swapped again. best(k) is the most money you can get. Both methods below compute best(12) from the same formula; they differ only in the order they visit states.

Output
1 / 13
4

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
5

Converting Between the Two

  1. List the parameters of the recursive function; they are the table's dimensions
  2. Turn each base case into an initial value in the table
  3. Look at which smaller states each call uses, and loop in the order that fills those first
  4. Replace every recursive call with a table lookup
  5. 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