Skip to lesson

Several recursive calls

When a recursive method makes two or more recursive calls that solve independent subproblems (like splitting an array into left and right halves), it stays fast. When those branches repeatedly solve the exact same subproblems over and over again, runtime explodes exponentially—until you add a 3-line cache called memoization.

Why plain Fibonacci is slow

Look at fib(n) = fib(n - 1) + fib(n - 2): to compute fib(50) it calls fib(49) and fib(48), and fib(49) calls fib(48) again.

Example 1 · Plain fib(n) vs memoized fib(n): call count comparison

FibMemoComparisonDemo.javaJava
import java.util.Arrays;
public class FibMemoComparisonDemo {    static long plainCalls, memoCalls;
    public static long fibPlain(int n) {        plainCalls++;        if (n <= 1) return n;        return fibPlain(n - 1) + fibPlain(n - 2);    }
    public static long fibMemo(int n, long[] memo) {        memoCalls++;        if (n <= 1) return n;        if (memo[n] != -1) return memo[n];        memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);        return memo[n];    }
    public static void main(String[] args) {        int n = 30;        long ans1 = fibPlain(n);        long[] memo = new long[n + 1];        Arrays.fill(memo, -1L);        long ans2 = fibMemo(n, memo);        System.out.println("fib(30) = " + ans1 + " (match: " + (ans1 == ans2) + ")");        System.out.println("plainCalls = " + plainCalls + ", memoCalls = " + memoCalls);    }}
Output
fib(30) = 832040 (match: true)
plainCalls = 2692537, memoCalls = 59

What this code does

  • For n = 30, plain recursion makes 2,692,537 calls, whereas memoized recursion makes only 59 calls (2n - 1)!
  • For n = 50, fibMemo makes just 99 calls and finishes in microseconds.
  • To compute fib(50), it calls fib(49) and fib(48).
  • fib(49) also calls fib(48) and fib(47).
  • So the whole subtree of fib(48) is computed twice from scratch, fib(47) 3 times, fib(46) 5 times, and fib(2) is computed 7,778,742,049 times!

Even though there are only n + 1 distinct inputs (0, 1, 2, ..., n), plain recursion recomputes them about 1.618ⁿ times. This is called overlapping subproblems: whenever a recursion tree has many nodes with the exact same arguments, plain recursion is doing wasted duplicate work.

Counting paths in a grid

Overlapping subproblems appear in 2D too. A robot starts at the top-left of an R × C grid and may only move Right or Down to the bottom-right cell (Unique Paths).

Example 2 · Counting Unique Paths in an R x C grid with 2D memoization

GridUniquePathsMemoDemo.javaJava
import java.util.Arrays;
public class GridUniquePathsMemoDemo {    public static long uniquePaths(int R, int C) {        long[][] memo = new long[R][C];        for (long[] row : memo) Arrays.fill(row, -1L);        return countPaths(0, 0, R, C, memo);    }
    private static long countPaths(int r, int c, int R, int C, long[][] memo) {        if (r >= R || c >= C) return 0L;        if (r == R - 1 && c == C - 1) return 1L;        if (memo[r][c] != -1L) return memo[r][c];
        memo[r][c] = countPaths(r + 1, c, R, C, memo) + countPaths(r, c + 1, R, C, memo);        return memo[r][c];    }
    public static void main(String[] args) {        System.out.println("3x7 grid paths: " + uniquePaths(3, 7));        System.out.println("15x15 grid paths: " + uniquePaths(15, 15));    }}
Output
3x7 grid paths: 28
15x15 grid paths: 40116600

What this code does

  • The first time countPaths visits (r, c), it computes the sum of down and right paths and stores it in memo[r][c].
  • Every subsequent visit to (r, c) returns memo[r][c] immediately in O(1) time, so each cell is expanded at most once: O(R * C) time and space.

From cell (r, c), the number of paths follows three rules:

  • Base case 1 (out of bounds): if r >= R || c >= C, return 0.
  • Base case 2 (destination reached): if r == R - 1 && c == C - 1, return 1.
  • Recursive case: paths(r + 1, c) + paths(r, c + 1).

Why is plain paths(0, 0) slow? Right-then-Down and Down-then-Right both land on (1, 1), so every cell is reached by many different prefixes and recomputed again and again: over 68 billion calls on a 20 × 20 grid, yet only 400 distinct cells.

Without caching, paths(0, 0) on a 20 × 20 grid makes over 68 billion recursive calls! Yet there are only 20 × 20 = 400 distinct (r, c) cells in the entire grid.

A first look at memoization

Memoization (from the Latin memorandum, "to be remembered") fixes overlapping subproblems without changing your recursive structure at all.

  1. Before making recursive calls, check if (memo[n] != -1) return memo[n];.
  2. Compute the recursive result as usual: long ans = fib(n - 1, memo) + fib(n - 2, memo);.
  3. Save and return: return memo[n] = ans;.

Example 3 · Brute force: plain recursion (O(2^n) time, O(n) space)

FibPlain.javaJava
public class FibPlain {    static long calls = 0;
    static long fib(int n) {        calls++;        if (n <= 1) return n;        return fib(n - 1) + fib(n - 2);    }
    public static void main(String[] args) {        System.out.println("fib(35) = " + fib(35));        System.out.println("Calls: " + calls);    }}
Output
fib(35) = 9227465
Calls: 29860703

What this code does

  • fib(35) makes 29,860,703 calls, because each call recomputes smaller values that were already computed elsewhere.
  • The recursion is only 35 frames deep, so memory is small; the problem is time.

Example 4 · Better: memoization remembers each answer (O(n) time, O(n) space)

FibMemo.javaJava
import java.util.Arrays;
public class FibMemo {    static long calls = 0;
    static long fib(int n, long[] memo) {        calls++;        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 void main(String[] args) {        long[] memo = new long[36];        Arrays.fill(memo, -1);        System.out.println("fib(35) = " + fib(35, memo));        System.out.println("Calls: " + calls);    }}
Output
fib(35) = 9227465
Calls: 69

What this code does

  • A memo array keeps each fib(i) after the first time it is computed, so only 69 calls are made instead of 29,860,703.
  • It is faster because each of the 36 distinct inputs is solved once, but it still spends O(n) memory on the array and the stack.

Example 5 · Optimal: two variables in a loop (O(n) time, O(1) space)

FibTwoVariables.javaJava
public class FibTwoVariables {    public static void main(String[] args) {        int n = 35;        long previous = 0, current = 1;        int additions = 0;        for (int i = 2; i <= n; i++) {            long next = previous + current;            previous = current;            current = next;            additions++;        }        System.out.println("fib(35) = " + current);        System.out.println("Additions: " + additions);    }}
Output
fib(35) = 9227465
Additions: 34

What this code does

  • fib(i) needs only the previous two values, so two variables replace the array: 34 additions and no recursion stack.
  • Time is the same as the memoized version, but memory drops from O(n) to O(1).

Example 6 · Climbing Stairs with 1, 2, or 3 steps (Tribonacci, / 1137)

ClimbingStairsMemoDemo.javaJava
import java.util.Arrays;
public class ClimbingStairsMemoDemo {    public static long waysToClimb(int n, long[] memo) {        if (n < 0) return 0L;        if (n == 0) return 1L; // 1 way to stay at step 0        if (memo[n] != -1L) return memo[n];        memo[n] = waysToClimb(n - 1, memo) + waysToClimb(n - 2, memo) + waysToClimb(n - 3, memo);        return memo[n];    }
    public static void main(String[] args) {        int n = 10;        long[] memo = new long[n + 1];        Arrays.fill(memo, -1L);        System.out.println("Ways to climb 10 stairs (1, 2, or 3 steps): " + waysToClimb(n, memo));    }}
Output
Ways to climb 10 stairs (1, 2, or 3 steps): 274

What this code does

  • Without memoization, 3 recursive calls per step would take O(3^n) time.
  • With memo[n], it computes each step 1..10 once in O(n) time.

Create an array memo (for example, long[] memo = new long[n + 1] filled with -1, or long[][] memo = new long[R][C] for a grid) and add two lines to your recursive method: Because each distinct state n (or (r, c)) is computed at most once and every subsequent call returns memo[n] in O(1) time, fib(n) drops from O(1.618ⁿ) to O(n) time, and uniquePaths(R, C) drops from O(2^(R+C)) to O(R · C) time!

Next step

Check your understanding

10 quick questions