Dynamic Programming Introduction

How to stop a recursive solution from doing the same work twice, shown step by step on the Fibonacci numbers.

Suppose you have added up a long column of numbers, and someone writes one more number at the bottom. You do not start again from the top. You take the total you already have and add the new number.

Dynamic programming (DP for short) turns that habit into a method. It builds the answer to a problem from the answers to smaller copies of the same problem, and it writes each of those answers down so none is worked out twice. It fits problems that ask how many ways something can be done, or for the cheapest, longest or best result.

The running example: Fibonacci numbers

The Fibonacci numbers start with 0 and 1, and each number after that is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, and so on. Counting from position 0, write F(n) for the number at position n. So F(0) = 0, F(1) = 1, and F(n) = F(n - 1) + F(n - 2) for every n from 2 up.

The task is small: given n, return F(n).

Example 1
Input: n = 5
Output: 5
Explanation: positions 0 to 5 hold 0, 1, 1, 2, 3, 5.
Example 2
Input: n = 10
Output: 55

It is a good first problem because the main DP ideas show up in it, and the numbers stay small enough to check by hand.

Plain recursion and its repeated work

What is the most direct way to compute F(5)? Copy the definition into code. To get F(5), ask for F(4) and F(3) and add them. The method below does exactly that, and it calls itself twice for every n above 1:

Java
static int fibRecursive(int n) {
    if (n <= 1) {
        return n;
    }
    return fibRecursive(n - 1) + fibRecursive(n - 2);
}
Recursion tree of F(5) with 15 calls. The F(2) under F(4) and the F(3) under F(5), with every call below them, are orange: 8 calls that repeat work done elsewhere in the tree.

The picture shows every call this method makes for F(5). Each rounded box is one call. F(5) at the top calls F(4) and F(3), F(4) calls F(3) and F(2), and so on down to F(1) and F(0), which return at once. There are 15 boxes, so 15 calls.

Now look at the orange boxes. The orange F(3) on the right does exactly the same work as the blue F(3) on the left, just below F(4). The orange F(2) under F(4) repeats the blue F(2) below that F(3). Eight of the 15 calls redo work that is done somewhere else in the tree.

The waste grows fast. Each call above F(1) starts two more, and the tree is n levels deep, so the number of calls is at most 2n. The true count is lower but still multiplies as n grows. The program further down counts the calls: F(5) takes 15, but F(30) takes 2,692,537.

Remembering answers: memoization

What if each answer were written down the first time it is worked out? Keep a map from n to F(n), here called memo. Before working on F(n), the method looks in memo. If F(n) is already there, it returns the stored value straight away. If not, it computes F(n) as before and stores the result.

Storing F(3) after its first call, so that the second F(3) costs one map lookup, is called memoization. The word comes from "memo", a note you write to yourself.

Recursion tree of F(5) with memoization: 9 calls. The second F(2) and the second F(3) are teal and answered from memo, so their branches are gone.

Compare this tree with the first one. The left side runs as before: F(5), F(4), F(3), F(2), F(1), F(0), then F(1) again. By the time F(4) asks for F(2), memo already holds it, so the teal box marked "from memo" returns without calling anything. The same happens to the teal F(3) on the right.

The tree shrinks from 15 calls to 9, and the counted run below shows F(30) dropping from 2,692,537 calls to 59. Each F(k) from 2 to n is now computed once, and every other call is a base case or a lookup.

This version still starts from the big question, F(5), and works down to smaller ones as they are needed. That is why it is called top-down.

Filling a table: tabulation

Every F(k) from 0 to n gets computed anyway. Why not compute them in order, smallest first, with no recursion at all?

Make an array dp with n + 1 entries, where dp[i] is the Fibonacci number at position i. Fill in the two starting values, dp[0] = 0 and dp[1] = 1, which are called the base cases. Then a loop fills each later entry from the two before it: dp[i] = dp[i - 1] + dp[i - 2].

The table dp for i = 0 to 5 holds 0, 1, 1, 2, 3, 5. Arrows from dp[3] and dp[4] show dp[5] = dp[4] + dp[3] = 3 + 2 = 5. Below, prev = F(3) holds 2 and curr = F(4) holds 3, and they add up to next = F(5), which holds 5.

Look at the row labelled dp[i] = F(i) in the picture. For i = 0 to 5 it holds 0, 1, 1, 2, 3, 5, and the first two boxes are the base cases. The orange arrows show the last step: dp[5] reads dp[4] = 3 and dp[3] = 2. Both are already filled, because the loop moves from left to right.

Working from the smallest answers up to the one you want is called bottom-up, and filling a table this way is called tabulation. Since nothing here calls itself, there is no chain of calls waiting for each other to return.

Keeping only the last two values

Look at the orange arrows once more. To fill dp[5], the loop reads only dp[4] and dp[3]. Nothing further left is ever read again, so the whole array is more than the loop needs.

Two variables are enough. In the part of the picture headed "keeping only the last two values", the box labelled prev = F(3) holds 2, the previous value, and the box labelled curr = F(4) holds 3, the current one. Their sum goes into the box labelled next = F(5), which holds 5. Then prev becomes 3 and curr becomes 5, ready for F(6).

Memory drops from n + 1 entries to a handful of numbers. Many table solutions end with this step, once it is clear how far back each entry looks.

Spotting a problem that fits

How do you tell that a new problem will give way to this approach? The Fibonacci example shows the two signs to look for.

  • The answer is built from answers to smaller copies of the same question. F(5) is F(4) + F(3), and nothing else is needed. In problems that ask for a best value, this property is called optimal substructure: the best answer for a large input is made from the best answers for smaller ones.
  • The smaller copies repeat. The orange boxes in the first tree are this sign, and it is called overlapping subproblems. Binary search also splits a problem into a smaller one, but it never meets the same piece twice, so it has nothing worth remembering.

The wording of a problem often gives it away too: "how many ways", "the minimum cost", "the longest", or "is it possible", where each step makes one of a few choices. Sometimes one number is not enough to describe a smaller copy. Counting paths across a grid, for example, needs a row and a column, so the table has two dimensions instead of one.

Once a problem fits, the Fibonacci steps carry over almost unchanged:

  1. Say in words what one entry means: dp[i] is the Fibonacci number at position i.
  2. Write how an entry comes from smaller ones: dp[i] = dp[i - 1] + dp[i - 2].
  3. Set the base cases: dp[0] = 0 and dp[1] = 1.
  4. Choose a fill order in which every entry you read is already filled: i from 2 up to n.
  5. Check how far back each entry looks, and keep only that much: here, the last two values.

The four versions in Java

The class below puts all four versions side by side:

  • Plain recursion, as in the first tree, is fibRecursive.
  • Memoization is fibMemo: the same recursion with a HashMap called memo, created once by the one-argument fibMemo(n) and passed down to every call.
  • Tabulation is fibTable, which fills the dp array from index 2 upwards.
  • The two-variable version is fib, the same loop with prev and curr in place of the array.
  • One extra method, fibLong, is the two-variable loop again with long in place of int, for the large values of n tried at the end of main.
  • A counter named calls goes up on every call of either recursive version.

Every version returns n itself for n = 0 and n = 1, before it touches the table or the variables. The main method checks that the four versions agree for n = 0, 1, 5 and 10. It also prints the table values for n = 0 to 10 and counts calls for n = 5 and 30. Last, it tries larger values of n with int and long, and calls fibMemo with n = 100,000.

Java
import java.util.HashMap;
import java.util.Map;

public class Fibonacci {
    static long calls = 0; // counts calls, so main can show how much work each version does

    // 1. Plain recursion: follows the definition, repeats work
    static int fibRecursive(int n) {
        calls++;
        if (n <= 1) {
            return n;
        }
        return fibRecursive(n - 1) + fibRecursive(n - 2);
    }

    // 2. Top-down with memoization: same recursion, answers kept in a map
    static int fibMemo(int n) {
        return fibMemo(n, new HashMap<>());
    }

    private static int fibMemo(int n, Map<Integer, Integer> memo) {
        calls++;
        if (n <= 1) {
            return n;
        }
        Integer known = memo.get(n);
        if (known != null) {
            return known; // F(n) was already worked out
        }
        int result = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
        memo.put(n, result);
        return result;
    }

    // 3. Bottom-up tabulation: fill dp[0..n] from the smallest index up
    static int fibTable(int n) {
        if (n <= 1) {
            return n;
        }
        int[] dp = new int[n + 1];
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }

    // 4. Bottom-up with two variables: only the last two values are kept
    static int fib(int n) {
        if (n <= 1) {
            return n;
        }
        int prev = 0; // F(i - 2)
        int curr = 1; // F(i - 1)
        for (int i = 2; i <= n; i++) {
            int next = prev + curr;
            prev = curr;
            curr = next;
        }
        return curr;
    }

    // The same loop with long, which holds Fibonacci numbers up to F(92)
    static long fibLong(int n) {
        if (n <= 1) {
            return n;
        }
        long prev = 0;
        long curr = 1;
        for (int i = 2; i <= n; i++) {
            long next = prev + curr;
            prev = curr;
            curr = next;
        }
        return curr;
    }

    public static void main(String[] args) {
        for (int n : new int[] {0, 1, 5, 10}) {
            System.out.println("n = " + n + ": recursive " + fibRecursive(n) + ", memo "
                    + fibMemo(n) + ", table " + fibTable(n) + ", two variables " + fib(n));
        }

        StringBuilder row = new StringBuilder("fibTable for n = 0 to 10:");
        for (int n = 0; n <= 10; n++) {
            row.append(' ').append(fibTable(n));
        }
        System.out.println(row);

        for (int n : new int[] {5, 30}) {
            calls = 0;
            fibRecursive(n);
            long plain = calls;
            calls = 0;
            fibMemo(n);
            System.out.println("Calls for n = " + n + ": recursive " + plain + ", memo " + calls);
        }

        System.out.println("int:  F(46) = " + fib(46) + ", F(47) = " + fib(47));
        System.out.println("long: F(47) = " + fibLong(47) + ", F(92) = " + fibLong(92)
                + ", F(93) = " + fibLong(93));

        try {
            fibMemo(100000);
            System.out.println("fibMemo(100000) finished");
        } catch (StackOverflowError e) {
            System.out.println("fibMemo(100000): StackOverflowError");
        }
    }
}

Running it prints:

Output
n = 0: recursive 0, memo 0, table 0, two variables 0
n = 1: recursive 1, memo 1, table 1, two variables 1
n = 5: recursive 5, memo 5, table 5, two variables 5
n = 10: recursive 55, memo 55, table 55, two variables 55
fibTable for n = 0 to 10: 0 1 1 2 3 5 8 13 21 34 55
Calls for n = 5: recursive 15, memo 9
Calls for n = 30: recursive 2692537, memo 59
int:  F(46) = 1836311903, F(47) = -1323752223
long: F(47) = 2971215073, F(92) = 7540113804746346429, F(93) = -6246583658587674878
fibMemo(100000): StackOverflowError

The first four lines show the versions agreeing: 0, 1, 5 and 55. The line starting fibTable for n = 0 to 10 lists 0, 1, 1, 2, 3, 5, the same values as the row labelled dp[i] = F(i) in the table picture, and goes on to 55.

The two lines starting Calls for match the trees: 15 calls against 9 for n = 5. For n = 30 the plain recursion makes 2,692,537 calls, while memoization makes 59.

The line starting int: shows the first trap. F(46) = 1836311903 is correct, but F(47) prints -1323752223. The true F(47) is 2,971,215,073, too large for an int, so the addition wrapped around into the negative numbers without any error. The next line shows the fix: with long, F(47) comes out right and the values stay correct up to F(92). F(93) wraps around too, so beyond that you need BigInteger.

The last line shows the second trap. The call fibMemo(100000) has to go 100,000 calls deep before the first answer comes back, and the thread's stack ran out first, so it threw StackOverflowError. The loop versions build no such chain of calls, which makes tabulation the safer choice when n can be large.

The original implementation, Fibonacci.java, is on GitHub.

Complexity

All four versions return the same numbers, but they pay very different prices in calls and memory:

  • Plain recursion: Time is O(2n), because each call above F(1) starts two more on a tree n levels deep. Space is O(n), because at most n calls wait for each other at once, along one path from F(n) down to F(1).
  • Memoization: Time is O(n), because each F(k) is computed once and every other call is a base case or a map lookup. Space is O(n), for the entries in memo, one for each k from 2 to n, and the chain of waiting calls.
  • Tabulation: Time is O(n), because the loop does one addition for each entry from 2 to n. Space is O(n), for the n + 1 entries of dp.
  • Two variables: Time is O(n), because it runs the same loop. Space is O(1), because it keeps the same few numbers however large n is.

Where to go next

Problems where each entry looks back a fixed one, two or three steps, like Fibonacci:

  • Climbing Stairs counts the ways up a staircase taken one or two steps at a time, and the counts turn out to be Fibonacci numbers.
  • Min Cost Climbing Stairs keeps the same two-step shape, but each entry is a cost: the cheaper of the two steps below, each with its own price added.
  • House Robber decides at each house whether to take it or skip it, again using only the last two entries.
  • N-th Tribonacci Number adds the last three numbers instead of two.

Problems where each entry looks at many earlier entries:

  • Coin Change finds the fewest coins for each amount by trying each coin as the last one paid.
  • Word Break asks whether each prefix of a string can be split into dictionary words.
  • Longest Increasing Subsequence finds the longest run of increasing numbers, not necessarily next to each other, and each entry looks at every number before it.

Problems that need two numbers per entry, so the table is a grid:

  • Unique Paths counts paths across a grid, each cell from the cell above and the cell to its left.
  • Longest Common Subsequence fills one entry for every pair of positions in two strings.
  • Edit Distance uses the same kind of grid to count the fewest edits that turn one word into another.