askNib

A series by Nib · for a curious adult who has seen a little code but never studied algorithms

What is dynamic programming, really?

6 explainers, each one drawn by Nib. Read it here, or play it and he draws and says every page. Updated .

▶ Play from the startQuick reviewCheat sheet

the short answer

Dynamic programming is a way of solving a big problem by solving each smaller problem inside it exactly once and remembering the answer. It helps when the same small questions keep coming up again and when the best answer to the whole is built from the best answers to the pieces. Remembering the answers can turn a method that would take longer than a lifetime into one that takes a few dozen steps.

Part 1 of 6

What does it mean for a function to call itself?

▶ Play this partIts own page

Dynamic programming is built on a trick called recursion, so we start there. Suppose you want the sum of the numbers from 1 to 4. You can say: it is 4, plus the sum of the numbers from 1 to 3. That is the same question, just smaller. A function that answers a question by asking a smaller copy of itself is called recursive.

Written as code, it reads like the sentence: the sum of n is n plus the sum of n minus one. Each call has its own value of n and waits for the answer from the call it made. Call it with 4 and it calls itself with 3, which calls itself with 2, and so on.

As written, that would never stop, because nothing tells the chain to end. So every recursive function needs a second part, a base case: a question so small that it can be answered directly. Here the sum of the numbers from 1 to 1 is just 1. Recursion is not circular, then. It only runs forever if the base case is missing or never reached.

Trace it. The call for 4 calls the call for 3, which calls the call for 2, which calls the call for 1, which returns 1. Then the answers climb back: 1, then 3, then 6, then 10. Every recursive function has the same two parts: a case that shrinks the problem, and a base case that stops the shrinking.

A recursive function trusts a smaller copy of itself and ends at a base case that needs no further calls.

Part 2 of 6

Why does the obvious Fibonacci recursion explode?

▶ Play this partIts own page

Now a famous example. The Fibonacci numbers run 0, 1, 1, 2, 3, 5, 8: after the first two, each number is the sum of the two before it. That definition translates directly into a recursive function: fib of n is fib of n minus one plus fib of n minus two, with fib of 0 equal to 0 and fib of 1 equal to 1 as the base cases.

Draw what happens when you ask for fib of 5. It calls fib of 4 and fib of 3, and each of those calls two more, down to the base cases. Now look for repeats. Fib of 3 appears twice in the tree. Fib of 2 appears three times. Each copy does all its work again from scratch, as if nobody had ever answered the question.

Counting the calls shows how quickly this adds up. Computing fib of 5 takes 15 calls; fib of 10 takes 177; fib of 20 takes 21,891; fib of 30 takes more than two and a half million. Each step up multiplies the work by about 1.6, which is exponential growth: add 10 to n and the work grows roughly a hundredfold.

Here is the surprise. Computing fib of 30 involves only 31 different questions, fib of 0 up to fib of 30. Millions of calls, thirty-one distinct answers. The problem is not hard; the method is wasteful. The explosion comes from forgetting: we answer the same few questions over and over.

The blowup is pure repetition: only a handful of distinct questions exist, but we recompute them endlessly.

Part 3 of 6

What if you remember each answer the first time?

▶ Play this partIts own page

If forgetting is the problem, the fix is to remember. Add a notebook to the function. Before it computes anything, it looks the question up. If the answer is there, it returns it straight away. If not, it computes the answer, writes it in the notebook, and then returns it.

Trace fib of 5 with the notebook. Going down the left side, each value is computed once and stored. Later, when fib of 2 is needed again, it is already in the notebook, and that whole branch of the tree simply disappears. The first time a question is asked is a miss, and the answer gets stored. Every later time is a hit, and it comes back instantly.

Now count the work. Each of the n different questions after the first two is computed once, using a single addition of two stored numbers. That is about n steps instead of exponential growth. For n equal to 50 the plain recursion needs about forty billion calls, and the notebook version needs about fifty steps. Nothing about what is computed has changed, only how many times.

This trick of storing answers as you go is called memoization, a name that goes back to a 1968 paper by Donald Michie on “memo” functions. It is the first half of dynamic programming.

Same recursion, one notebook: each question is answered once, and an exponential blowup becomes a straight line.

Part 4 of 6

Can you skip the recursion and fill in a table instead?

▶ Play this partIts own page

Memoization works from the top down: it starts with the question you want and digs down, remembering answers as it goes. But for Fibonacci we can see in advance what is needed, because fib of n only ever uses the two smaller values. That means we already know the order in which to answer the questions, and we can skip the recursion altogether.

Draw a row of boxes numbered 0 to 6. Fill the base cases first: 0 in box 0 and 1 in box 1. Then loop from left to right. Box 2 is the sum of boxes 1 and 0, which is 1. Box 3 is 1 plus 1, which is 2. Each box just reads the two before it, and by box 6 you have 8.

This version is called tabulation, or bottom-up. It does the same work as memoization, about one step per box, and gets the same answer. The difference is only direction. Memoization recurses down from the question; tabulation loops up from the smallest cases.

There is one rule you must respect: order. Before you fill a box, everything it depends on must already be filled. That is why you cannot fill box 6 first; it needs boxes 5 and 4. Fill the smallest cases first, then build upward, and the answer is waiting in the last box.

Tabulation is memoization turned upside down: fill a table from the smallest case and the answer is in the last box.

Part 5 of 6

What makes a problem fit this trick?

▶ Play this partIts own page

Remembering answers worked beautifully for Fibonacci. Does it work for everything? No. The trick needs the problem to have a particular shape, and two properties describe it.

The first is overlapping subproblems: the same small questions keep coming up. In the Fibonacci tree the same values appear in several branches, so saving an answer pays off again and again. Compare sorting a list by splitting it in half and sorting each half. Every piece is different and nothing ever repeats, so a notebook would sit empty. Overlap is what earns the table.

The second is optimal substructure: the best answer to the whole problem is built from best answers to its pieces. That is why a saved answer can be trusted and simply plugged in. Think of the cheapest route from A to C that passes through B. The part from A to B must be the cheapest way to get from A to B. If it were not, you could swap in a cheaper one and improve the whole route, which contradicts its being the cheapest.

So ask two questions of a new problem. Do the small questions recur? Do the best pieces build the best whole? Two yeses and the trick applies. Dynamic programming is not a cure for slow recursion; it is a match between a method and a shape.

Dynamic programming fits when small questions recur and the best whole is built from best pieces.

Part 6 of 6

How do you use it on a brand-new problem, like fewest coins?

▶ Play this partIts own page

Here is a new problem. You have coins worth 1, 4 and 5, and you want to make 8 with as few coins as possible. A tempting rule is to grab the biggest coin first. That gives 5 + 1 + 1 + 1, which is four coins, but 4 + 4 does it in two. Greedy grabbing is not always best, and dynamic programming gives a way to be sure.

Step one: say what a table entry means. Let box a hold the fewest coins needed to make exactly the amount a. The answer we want will be box 8. Step two: say how a box depends on smaller boxes. Pick a last coin c. Then you need one coin, plus the best answer for the amount a minus c. Try every coin that fits and keep the smallest, so box a is 1 plus the minimum, over every coin c that fits, of box a minus c.

Step three: the base case. Making 0 takes 0 coins, so put 0 in box 0, and everything else grows from that. Step four: fill the boxes from left to right. For each one, check every coin and keep the smallest result. The table for coins 1, 4 and 5 reads 0, 1, 2, 3, 1, 1, 2, 3, 2. At box 8 the three options are 4, 2 and 4, and the smallest, 2, is the answer: two coins.

Those four moves are the same every time: define the entry, write its dependency, set the base case, fill in order. Fibonacci and the coins share one recipe. The name has an odd history: Richard Bellman, who developed the method in the 1950s, used “programming” in the older sense of planning, and by his own later account he liked that “dynamic” sounded impressive and was hard to object to. Whatever the name, the idea is four questions you can ask of any problem, and a table that answers them.

Dynamic programming is four questions you can ask of any problem, and a table that answers them.

Dynamic programming is recursion that remembers. Recursion breaks a problem into smaller copies, the notebook or the table makes sure each distinct copy is solved only once, and the two properties tell you when that is possible. That is how a method that needs millions of calls shrinks to a few dozen steps.

Quick review

The whole series in a few minutes: each part's last board, its one idea, and the lines worth keeping.

Part 1

What does it mean for a function to call itself?

A function solves a problem by asking a smaller copy of itself, and stops at a base case.

  • Solve a problem by asking the same question on something smaller.
  • A self-call is just a normal call, with its own fresh n.
  • The base case is the smallest problem, answered without calling again.
  • Calls go down to the base case; answers come back up and combine.
  • Two parts: a recursive case that shrinks, and a base case that stops.

Part 2

Why does the obvious Fibonacci recursion explode?

It keeps recomputing the same small values, so the work multiplies although the distinct questions are few.

  • The obvious code is just the definition: fib(n) = fib(n-1) + fib(n-2), with fib(0)=0 and fib(1)=1.
  • Every call branches into two more calls, so the calls form a tree that widens fast.
  • The tree contains the same subproblems again and again, and each copy is solved from scratch.
  • Total calls grow exponentially: fib(30) already needs over 2.6 million calls.
  • There are only n+1 distinct subproblems, but exponentially many calls to them.

Part 3

What if you remember each answer the first time?

Keep a notebook of answers and every distinct question is solved only once.

  • The waste is repeating questions you already answered; a notebook stops the repeats.
  • Check the notebook first; if missing, compute, save, return.
  • Repeated branches are replaced by one-step lookups, so the tree collapses.
  • n+1 distinct questions, each solved once, means work proportional to n.

Part 4

Can you skip the recursion and fill in a table instead?

Start from the smallest case and fill a table upward, so every entry finds its inputs ready.

  • Each answer depends only on smaller ones, so the order is predictable.
  • Start by writing the base cases into the table.
  • Loop upward; every box finds its inputs already filled.
  • Same work, opposite direction: top-down versus bottom-up.
  • Pick an order where every box's inputs come before it.

Part 5

What makes a problem fit this trick?

Two properties: the same small questions recur, and the best whole is built from best pieces.

  • The trick only works on problems with a particular shape, and two properties name it.
  • Overlapping subproblems: the same smaller questions keep coming back, so saved answers get reused.
  • If subproblems never repeat, memory buys nothing; plain recursion is enough.
  • Optimal substructure: best answers to small pieces combine into the best answer to the whole.
  • If the best whole contains a worse piece, you could swap in a better piece, so best wholes use best pieces.
  • Two yes answers (recurring questions, best-from-best) mean dynamic programming fits.

Part 6

How do you use it on a brand-new problem, like fewest coins?

Four moves: say what a table entry means, how it depends on smaller entries, where it starts, and fill in order.

  • A fresh problem needs a method, not a hunch.
  • First, say in words what one entry means.
  • Last coin c costs 1 plus the best for what's left.
  • best(a) = 1 + min over coins c of best(a − c).
  • Base case: amount 0 needs 0 coins.
  • For each box, try every coin and keep the smallest.
  • Meaning, dependency, base case, fill order: the recipe for any new problem.

Cheat sheet

One sheet: every part's key drawing and its key line.

  1. 1. What does it mean for a function to call itself? A function solves a problem by asking a smaller copy of itself, and stops at a base case.

  2. 2. Why does the obvious Fibonacci recursion explode? It keeps recomputing the same small values, so the work multiplies although the distinct questions are few.

  3. 3. What if you remember each answer the first time? Keep a notebook of answers and every distinct question is solved only once.

  4. 4. Can you skip the recursion and fill in a table instead? Start from the smallest case and fill a table upward, so every entry finds its inputs ready.

  5. 5. What makes a problem fit this trick? Two properties: the same small questions recur, and the best whole is built from best pieces.

  6. 6. How do you use it on a brand-new problem, like fewest coins? Four moves: say what a table entry means, how it depends on smaller entries, where it starts, and fill in order.