Skip to lesson

Memoization augments top-down recursive functions with a lookup cache to avoid redundant subproblem evaluations.

Top-down memoization mechanics

Memoization is storing the result of a recursive call the first time it is computed and returning the stored result when the same call happens again (top-down DP).

Top-down recursive solutions naturally mirror mathematical problem descriptions. However, exploring all branches without memory causes exponential recursion depth. Memoization intercepts every recursive invocation before executing expensive child calls.

Step by step

Step 1 of 6

Array: -1, -1, -1, -1, -1, -1.
step
0
memoSize
6
Initialize memo table of size 6 with sentinel value -1.

Example 1 · Top-Down Memoized Fibonacci

MemoFibonacciSentinel.javaJava
import java.util.Arrays;
public class MemoFibonacciSentinel {    public static int fib(int n, int[] memo) {        if (n <= 1) return n;        if (memo[n] != -1) return memo[n];        memo[n] = fib(n - 1, memo) + fib(n - 2, memo);        return memo[n];    }
    public static int calculateFib(int n) {        int[] memo = new int[n + 1];        Arrays.fill(memo, -1);        return fib(n, memo);    }
    public static void main(String[] args) {        System.out.println("Fib(6): " + calculateFib(6));        System.out.println("Fib(10): " + calculateFib(10));    }}
Output
Fib(6): 8
Fib(10): 55

What this code does

  • Arrays.fill initializes the memo array with -1 to signify unvisited subproblems.
  • Base cases 0 and 1 return immediately without consulting the memo table.
  • Subproblems calculate once and return in O(1) time on subsequent visits.

At the start of the function, check if the current state exists in memory. If the cached value exists, return it immediately in O(1) time. Otherwise, evaluate the recursive transitions, store the result, and return it. This simple pattern prunes duplicate subtrees across the entire execution. Each unique state gets calculated exactly once. The overall time complexity becomes proportional to the number of distinct states.

Order of execution

Order one memoized call

Tap the five steps in the order the function runs them.

static int fib(int n, int[] memo) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n];
memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
return memo[n];
}

Choosing array versus hash map caches

The choice of cache structure depends on the domain of the state space. When state parameters are dense non-negative integers, primitive arrays excel. Array indexing provides cache locality and zero object boxing overhead.

Example 2 · Memoized Climbing Stairs with an Array

ClimbStairsMemo.javaJava
public class ClimbStairsMemo {    public static int climb(int n, Integer[] memo) {        if (n <= 2) return n;        if (memo[n] != null) return memo[n];        memo[n] = climb(n - 1, memo) + climb(n - 2, memo);        return memo[n];    }
    public static void main(String[] args) {        int n = 5;        Integer[] memo = new Integer[n + 1];        System.out.println("Ways for " + n + ": " + climb(n, memo));        int n2 = 6;        Integer[] memo2 = new Integer[n2 + 1];        System.out.println("Ways for " + n2 + ": " + climb(n2, memo2));    }}
Output
Ways for 5: 8
Ways for 6: 13

What this code does

  • An Integer array allows null checks directly instead of filling sentinel values.
  • Reaching step n splits into step n - 1 and step n - 2 recursive inquiries.
  • Outputs 8 and 13 confirm path count expansion for 5 and 6 steps.

Example 3 · Coin Change with a HashMap Memo

CoinChangeMemoMap.javaJava
import java.util.HashMap;import java.util.Map;
public class CoinChangeMemoMap {    public static int minCoins(int rem, int[] coins, Map<Integer, Integer> memo) {        if (rem == 0) return 0;        if (rem < 0) return -1;        if (memo.containsKey(rem)) return memo.get(rem);
        int min = Integer.MAX_VALUE;        for (int coin : coins) {            int res = minCoins(rem - coin, coins, memo);            if (res >= 0 && res < min) {                min = res + 1;            }        }        int ans = (min == Integer.MAX_VALUE) ? -1 : min;        memo.put(rem, ans);        return ans;    }
    public static void main(String[] args) {        int[] coins = {1, 2, 5};        Map<Integer, Integer> memo = new HashMap<>();        System.out.println("Coins for 11: " + minCoins(11, coins, memo));        memo.clear();        System.out.println("Coins for 7: " + minCoins(7, coins, memo));    }}
Output
Coins for 11: 3
Coins for 7: 2

What this code does

  • A HashMap handles targets dynamically without allocating fixed-length arrays.
  • Invalid transitions returning -1 are stored to prune dead-end branches.
  • Amounts 11 and 7 yield optimal counts of 3 and 2 coins.

Use sentinel values like negative one to differentiate uncomputed states from genuine zero answers. If zero represents a valid answer, boolean visited arrays prevent repeated zero recomputations. Primitive arrays deliver the fastest execution times in competitive programming. When state parameters are sparse, negative, or multi-dimensional keys, use hash maps. Hash maps avoid preallocating giant arrays when few states are ever visited. However, hash maps incur object boxing and hashing overhead on every lookup.

Recursion call stack and memory overhead

Memoization relies on the call stack to maintain execution context across transitions. Each recursive call allocates a frame containing local variables and return addresses. If the recursion depth reaches thousands of frames, a StackOverflowError can occur.

In Java, the default JVM stack size is typically one megabyte. Linear state graphs with large n can exhaust stack space even with memoization. Bottom-up tabulation avoids call stack growth by using iterative loops instead.

Despite stack overhead, memoization offers one distinct advantage over tabulation. Memoization computes only states reachable from the initial root call. Tabulation might fill unnecessary table cells that cannot affect the final goal.

Next step

Check your understanding

10 quick questions