Introduction to Dynamic Programming

How dynamic programming speeds up recursive solutions with memoisation and tabulation, using a coin-change example, and what interviewers ask.

14 minLesson 1 of 6
On this page
  1. Plain recursion and where it wastes time
  2. Memoisation: remembering answers while recursing
  3. Tabulation: filling a table from the smallest case
  4. The five questions to answer for any DP problem
  5. Time and space complexity
  6. Memoisation or tabulation
  7. Variants of the coin problem
  8. In the interview
  9. What to practise next

Dynamic programming is a way of solving a problem by splitting it into smaller subproblems, solving each distinct subproblem only once, and reusing the stored answer whenever the same subproblem comes up again. It is used for problems where a plain recursive solution repeats the same work an exponential number of times. You reach for it when you are asked for the minimum, the maximum or the number of ways to do something, and the best answer for a large input is built from the best answers for smaller inputs.

Without it, a recursive solution to such a problem can take far longer than the input size suggests. The coin problem used throughout this lesson is a good example: given coins worth 1, 4 and 5, find the fewest coins that add up to 8. Taking the biggest coin first gives 5 + 1 + 1 + 1, which is four coins, but 4 + 4 is only two. A greedy rule fails here (see Greedy Algorithms), so the solution has to consider every possible first coin.

Plain recursion and where it wastes time

The first coin is a 1, a 4 or a 5, and what remains to pay is the same problem with a smaller amount. The fewest coins for 8 is therefore one coin plus the best of the answers for 7, 4 and 3, and each of those splits the same way until the amount reaches 0, which needs no coins.

Plain recursion: try every first coin
// Fewest coins that add up to amount (Infinity if impossible).
function fewestCoins(amount, coins) {
  if (amount === 0) return 0;
  let best = Infinity;
  for (const coin of coins) {
    if (coin <= amount) {
      best = Math.min(best, 1 + fewestCoins(amount - coin, coins));
    }
  }
  return best;
}
 
fewestCoins(8, [1, 4, 5]); // 2
import math
 
# Fewest coins that add up to amount (math.inf if impossible).
def fewest_coins(amount, coins):
    if amount == 0:
        return 0
    best = math.inf
    for coin in coins:
        if coin <= amount:
            best = min(best, 1 + fewest_coins(amount - coin, coins))
    return best
 
fewest_coins(8, [1, 4, 5])  # 2

This is correct, but for an amount of 8 it makes 35 calls, and for 30 it makes 255,904. There are only 31 different amounts from 0 to 30, so nearly all of those calls repeat work that was already done.

−1 −4 −5 8 7 4 3 6 3 2 3 0 2
The first three levels of the calls for fewestCoins(8). The amount 3 is solved three separate times.

This is the same waste as the naive Fibonacci function in Recursion. A problem is a candidate for dynamic programming when two things are true. First, the answer for the whole problem can be computed from the answers to smaller versions of it; here, the best way to pay 8 is one coin plus the best way to pay what is left. Second, the smaller versions repeat, meaning that different paths through the recursion keep arriving at the same amount.

Memoisation: remembering answers while recursing

Memoisation keeps a map from each subproblem to its answer. Before computing a subproblem, the function looks in the map, and after computing one it stores the result. Each amount is then solved once, and every later visit is a lookup. This is also called the top-down approach, because you start from the full problem and let the recursion find the subproblems it needs.

Memoised: the same recursion plus a map
function fewestCoinsMemo(amount, coins, memo = new Map()) {
  if (amount === 0) return 0;
  if (memo.has(amount)) return memo.get(amount); // solved before
  let best = Infinity;
  for (const coin of coins) {
    if (coin <= amount) {
      best = Math.min(best, 1 + fewestCoinsMemo(amount - coin, coins, memo));
    }
  }
  memo.set(amount, best); // remember for next time
  return best;
}
def fewest_coins_memo(amount, coins, memo=None):
    if memo is None:
        memo = {}
    if amount == 0:
        return 0
    if amount in memo:  # solved before
        return memo[amount]
    best = math.inf
    for coin in coins:
        if coin <= amount:
            best = min(best, 1 + fewest_coins_memo(amount - coin, coins, memo))
    memo[amount] = best  # remember for next time
    return best

For an amount of 30 the number of calls drops from 255,904 to 84. The recursion itself did not change; the function simply stopped discarding answers it had already computed. The map must be created once and passed down, not created inside the function body, because otherwise every call gets its own empty map and nothing is reused. In Python, do not write memo={} as a default argument, because that dictionary is shared between separate calls, and answers computed for one set of coins would leak into the next. The code above uses None for that reason.

Tabulation: filling a table from the smallest case

Every amount depends only on smaller amounts, so the recursion can be replaced by a loop that works upward from 0. By the time the loop reaches an amount, every answer that amount needs is already in the table. This is the bottom-up approach, called tabulation. The trace below fills the table for coins 1, 4 and 5 and an amount of 8.

Fill best[a] for every amount up to 8Use the arrows or ← → keys
best = [∞] * (amount + 1)best[0] = 0for a from 1 to amount:  for coin in coins:    if coin <= a:      best[a] = min(best[a], 1 + best[a - coin])return best[amount]
  1. best
    00
    1∞
    2∞
    3∞
    4∞
    5∞
    6∞
    7∞
    8∞
    coins
    1, 4, 5

    1The table has one slot for each amount from 0 to 8, and every slot starts at ∞, which means no way of paying has been found yet. Paying 0 needs 0 coins, so best[0] = 0.

  2. best
    00
    11a
    2∞
    3∞
    4∞
    5∞
    6∞
    7∞
    8∞
    a
    1
    best[a]
    1

    2For amount 1 only coin 1 fits, and it leaves 0. So best[1] = 1 + 0 = 1.

  3. best
    00
    11
    22a
    3∞
    4∞
    5∞
    6∞
    7∞
    8∞
    a
    2
    best[a]
    2

    3For amount 2 only coin 1 fits, and it leaves 1. So best[2] = 1 + 1 = 2.

  4. best
    00
    11
    22
    33a
    4∞
    5∞
    6∞
    7∞
    8∞
    a
    3
    best[a]
    3

    4For amount 3 only coin 1 fits, and it leaves 2. So best[3] = 1 + 2 = 3.

  5. best
    00
    11
    22
    33
    41a
    5∞
    6∞
    7∞
    8∞
    a
    4
    best[a]
    1

    5For amount 4 each coin is tried and the remainder is looked up. Coin 1 leaves 3, giving 1 + 3 = 4. Coin 4 leaves 0, giving 1 + 0 = 1. The smaller value, 1, is kept.

  6. best
    00
    11
    22
    33
    41
    51a
    6∞
    7∞
    8∞
    a
    5
    best[a]
    1

    6For amount 5, coin 1 leaves 4, giving 1 + 1 = 2. Coin 4 leaves 1, giving 1 + 1 = 2. Coin 5 leaves 0, giving 1 + 0 = 1. The smallest value is 1.

  7. best
    00
    11
    22
    33
    41
    51
    62a
    7∞
    8∞
    a
    6
    best[a]
    2

    7For amount 6, coin 1 leaves 5, giving 1 + 1 = 2. Coin 4 leaves 2, giving 1 + 2 = 3. Coin 5 leaves 1, giving 1 + 1 = 2. The smallest value is 2.

  8. best
    00
    11
    22
    33
    41
    51
    62
    73a
    8∞
    a
    7
    best[a]
    3

    8For amount 7, coin 1 leaves 6, giving 1 + 2 = 3. Coin 4 leaves 3, giving 1 + 3 = 4. Coin 5 leaves 2, giving 1 + 2 = 3. The smallest value is 3.

  9. best
    00
    11
    22
    33
    41
    51
    62
    73
    82a
    a
    8
    best[a]
    2

    9For amount 8, coin 1 leaves 7, giving 1 + 3 = 4. Coin 4 leaves 4, giving 1 + 1 = 2. Coin 5 leaves 3, giving 1 + 3 = 4. The smallest value is 2.

  10. best
    00
    11
    22
    33
    41
    51
    62
    73
    82
    answer
    2
    lookups
    17

    10The answer is best[8] = 2, which is two coins of value 4. The table needed 17 lookups, where plain recursion made 35 calls. For an amount of 30 it is 83 lookups against 255,904 calls.

1 / 10
Tabulation: a loop instead of recursion
function fewestCoinsTable(amount, coins) {
  const best = new Array(amount + 1).fill(Infinity);
  best[0] = 0;
  for (let a = 1; a <= amount; a++) {
    for (const coin of coins) {
      if (coin <= a) best[a] = Math.min(best[a], 1 + best[a - coin]);
    }
  }
  return best[amount]; // Infinity means "cannot be paid"
}
 
fewestCoinsTable(8, [1, 4, 5]); // 2
def fewest_coins_table(amount, coins):
    best = [math.inf] * (amount + 1)
    best[0] = 0
    for a in range(1, amount + 1):
        for coin in coins:
            if coin <= a:
                best[a] = min(best[a], 1 + best[a - coin])
    return best[amount]  # math.inf means "cannot be paid"
 
fewest_coins_table(8, [1, 4, 5])  # 2

The five questions to answer for any DP problem

Every dynamic programming solution can be designed by answering five questions in words before writing any code. The coin problem answers them like this.

  1. State. What does one cell of the table mean? Here, best[a] is the fewest coins that add up to exactly a.
  2. Recurrence. How is a cell computed from smaller cells? Here, best[a] is 1 plus the minimum of best[a − coin] over every coin that fits.
  3. Base cases. Which cells are known without computing? Here, best[0] = 0.
  4. Order. In what order can the cells be filled so that every cell's inputs are ready? Here, from 0 upward.
  5. Answer. Which cell holds the result? Here, best[amount].

The state is the hard part. If you cannot say in one sentence what a cell means, you will not be able to write the recurrence.

Time and space complexity

ApproachTimeSpaceWhy
Plain recursionExponentialO(A)A is the amount and k is the number of coins. Each call makes up to k calls and the recursion is up to A levels deep, so there are about kA calls.
MemoisationO(A × k)O(A)Each amount is solved once, and solving it tries k coins. The map and the call stack hold up to A entries.
TabulationO(A × k)O(A)The same work in two loops, with no call stack.

For any dynamic programming solution, the running time is the number of cells in the table multiplied by the work done per cell.

Memoisation or tabulation

Both do the same amount of work, and the choice is mostly about convenience. Memoisation is usually quicker to write correctly, because you take the recursive solution and add a map. Its weakness is the call stack: on a large input, such as an amount of 100,000, the recursion can exceed the stack limit, especially in Python. Tabulation has no such limit and is slightly faster because it avoids function calls, but you have to work out a valid fill order yourself. To check an order, pick one cell and confirm that every cell it reads has already been filled; if the coin loop above ran downward from 8, best[8] would read best[7], best[4] and best[3] before they were computed and would return ∞.

Variants of the coin problem

Counting the ways instead of finding the minimum

Some problems ask how many different ways there are to reach the target. The table then stores counts, and the recurrence adds the contributions of the choices where the coin problem took a minimum. The base case becomes ways[0] = 1, because there is exactly one way to pay 0, which is to use no coins. The order of the loops now matters. With the coin loop on the outside and the amount loop inside, each combination is counted once. With the amount loop on the outside, the same coins in a different order count as different ways, which solves a different problem.

Recovering the actual choices

The table holds the best value, not the sequence of choices that produced it. To report which coins were used, store the coin that gave the best value for each amount in a second array, then start at the target and repeatedly subtract the stored coin until you reach 0. For amount 8 the stored coin is 4 for both 8 and 4, so the walk gives 4, 4.

When the answer might not exist

With coins 4 and 5, the amount 3 cannot be paid. The table keeps ∞ in that cell, and any cell that depends on it is also ∞. Return -1 when the final cell is still ∞. This is also why the table starts at ∞ and not at 0: starting at 0 would make every answer 0, because a minimum never replaces a 0.

When dynamic programming does not apply

Dynamic programming needs overlapping subproblems. Merge sort splits its input into halves that never overlap, so storing answers would save nothing, and plain divide and conquer is the right description (see Divide and Conquer). It also needs the best answer for a problem to be built from the best answers for its subproblems. If a choice made early changes what is allowed later in a way that the state does not record, the table gives wrong answers, and the state has to be extended. When a simple rule is provably correct, such as coins that are all multiples of one another, a greedy solution is simpler. If the number of distinct states is itself exponential, the table is too large to be practical.

In the interview

Several phrases in a problem statement point to dynamic programming. The problem asks for the minimum, the maximum or the number of ways, or asks whether something is possible. A decision is made at each step, such as which coin to use or whether to take an item. A brute-force search over those decisions would be exponential, and the same partial situation can be reached by more than one route. When you see this, say that you will define what a table cell means, write the recurrence, and then decide between memoisation and a table.

Questions an interviewer is likely to ask:

  • "Why does greedy fail here?" Taking the largest coin at each step commits to a choice without checking where it leads. For coins 1, 4 and 5 and an amount of 8, greedy picks 5 and ends up with four coins, while 4 + 4 needs two. Dynamic programming compares every first coin, so it cannot be misled by an early choice.
  • "What is the time and space complexity?" Time is the number of table cells multiplied by the work per cell, which is O(A × k) here. Space is O(A) for the table, and memoisation also uses up to O(A) of call stack.
  • "Memoisation or tabulation, and why?" Say which you chose and give the trade-off. Memoisation follows directly from the recursion and computes only the states it needs, but a deep recursion can overflow the stack. Tabulation avoids that and allows space savings, but needs a fill order.
  • "Can you use less memory?" It depends on how far back a cell looks. In the coin problem a cell can read any smaller amount up to the largest coin, so you can keep only as many recent cells as the value of the largest coin. In problems where each cell reads only the previous one or two, two variables are enough.
  • "How would you return the coins, not just the count?" Store the chosen coin for each amount while filling the table, then walk back from the target subtracting stored coins until you reach 0.
  • "How do you decide what the state is?" Ask what you would need to know to continue the problem from the middle, without knowing how you got there. That information is the state. If the answer for a cell also depends on a detail the cell does not record, such as how many items have been used so far, add that detail to the state as another dimension of the table.
Quick check

The coins are 1, 3 and 4. Using the table, what is best[6]?

Why is memoised recursion so much faster than plain recursion for the coin problem?

Which of the five questions decides whether the table is filled upward or downward?

What to practise next

The coin table is a single row of cells, each reading a few earlier cells, and many problems have the same shape. They are covered in 1D Dynamic Programming. To practise the coin table itself, try Cookie Box Order.