dynamic programming · recursion · memoisation
Why dynamic programming is hard — and how to recognise it
Dynamic programming is hard: its cache key must capture every fact that changes the future. Drive this recurrence to find the right state — and reject fake DP.
The explanation you have been given
Every answer to this question is the same three moves. Find the overlapping subproblems. Write the recurrence. Cache the results.
Every word of that is true. I repeated it for about a year. And you cannot actually do anything with it.
Read the three moves again, and this time ask a different question about each one: when would you know you had done it right?
You can only tell that the subproblems overlap once you already know what the subproblems are. You can only check the recurrence once you already have the recurrence.
And caching is something you do to a recursion you already wrote. The recursion is the answer. Adding a dictionary to it is the last five minutes of the job.
So the advice starts one step after the part that was hard, and then describes what a finished solution looks like. It is a photograph of the destination handed to you as directions.
Which leaves two questions, and this page stays on them until the end.
Does this problem contain futures we can safely reuse? If it does, what facts identify one future?
One machine and five bookings
One build machine. Five teams have asked for it today. Each request has a start hour, an end hour, and the number of minutes of engineer time that run would save them.
The requests overlap, so somebody is getting turned down.
the day
09 10 11 12 13 14 15 16 17 18
A 70 [-------]
B 20 [---------------]
C 90 [-------]
D 60 [---------------]
E 50 [-----------]
Accept a set of bookings that never overlap, and make the total as large as you can.
That is the whole problem. Every scheduler you have ever used is doing some version of it.
Attempt 1: take the most valuable first
Sort by value, walk the list, and accept anything that still fits. C is worth 90 so it goes in. Then A at 70. Then D at 60. B and E no longer fit around them.
Total: 220 minutes. Check every possible answer and 220 turns out to be the best the day can do. Our rule got it exactly right.
That check is worth being precise about, because it is the only reason to believe the 220. There are exactly [32](#note-subsets) possible sets of bookings. A program built all 32, threw away every set with an overlap in it, and added up what was left.
The best surviving set was A, C and D, at 220.
Now one team revises their estimate. B is re-quoted from 20 to 100, and nothing else about the day changes at all. Same hours, same everything.
Our rule now grabs B first, because 100 is the biggest number on the board. B runs 09 to 13, which blocks A and blocks C. The rule answers 160. The day is still worth 220. We just lost an hour of somebody's time to a rule that looked fine yesterday.
Here is why no rule of that shape can work, and it is worth saying slowly.
What a booking costs you is not its value. It is whatever it blocks. And what it blocks has not happened yet.
So you cannot score the first choice on its own. You can only score it as two things added together: this booking's own value, plus the best you can do with whatever time is left afterwards.
And look carefully at that second half. "The best you can do with what is left" is the same question again, asked about a shorter day. A question that contains a smaller copy of itself is a question a function can answer by calling itself.
Attempt 2: try both, all the way down
So stop choosing. Take the bookings in order, and at each one try both branches: leave it out, or take it and carry forward the hour the machine becomes free.
The function needs two things to know where it is. Which booking we are looking at, and when the machine is next free.
python
def best(i, free_at):
if i == len(bookings):
return 0
start, end, value = bookings[i]
without = best(i + 1, free_at)
if start < free_at: # the machine is busy
return without # so this one is not an option
return max(without, value + best(i + 1, end))java
int best(int i, int freeAt) {
if (i == bookings.length) return 0;
int start = bookings[i][0];
int end = bookings[i][1];
int value = bookings[i][2];
int without = best(i + 1, freeAt);
if (start < freeAt) return without; // busy
return Math.max(without, value + best(i + 1, end));
}c++
int best(int i, int freeAt) {
if (i == n) return 0;
auto [start, end, value] = bookings[i];
int without = best(i + 1, freeAt);
if (start < freeAt) return without; // busy
return max(without, value + best(i + 1, end));
}javascript
function best(i, freeAt) {
if (i === bookings.length) return 0;
const [start, end, value] = bookings[i];
const without = best(i + 1, freeAt);
if (start < freeAt) return without; // busy
return Math.max(without, value + best(i + 1, end));
}
This is correct, and it is correct for a reason worth naming: it never decides anything. It just tries everything and reports the best it saw.
On our five bookings it returns 220, and it takes [36 calls](#note-calls) to get there.
Thirty-six is nothing. Then you run it on a day with more bookings in it.
measured
bookings calls the plain recursion makes
10 288
15 3,569
20 51,501
25 273,381
30 2,641,619
How much of that work is work we already did
Before reaching for a cache, it is worth knowing whether a cache would even help. A cache only helps if the same question is being asked more than once.
So let us count. Not the calls this time. The different questions.
A question here is a pair: which booking, and when the machine is free. (booking C, machine free at 13) is a question. Ask it twice and you get the same answer twice, because nothing else in the world has changed.
On our day, the 36 calls ask 18 different questions. The other 18 calls are questions we had already answered.
That is easier to believe when you can see it, so here is the whole recursion drawn out. Every box is one call, and it sits under the call that made it.
The filled boxes are the ones worth looking at. Press any question underneath and watch where else in the tree it turns up.
Notice the shape. The far-left path down is almost all empty boxes, and almost everything to the right of it is filled. That is the first walk discovering the whole problem, and then the rest of the tree doing it again.
And look at where a repeat comes from. Taking B leaves the machine free at 13. So does taking A and then C. From there on, the rest of the day is the same problem in exactly the same words. The tree has no idea, so it walks it twice.
Now press "ask each question only once". The repeated boxes fall away and 36 becomes 18, with nothing lost: every box that disappeared was asking something another box had already answered.
That is the entire idea of a cache, and you just watched it happen on five bookings.
measured
bookings calls different questions
5 36 18
10 288 54
15 3,569 106
20 51,501 173
25 273,381 250
30 2,641,619 360
Look at the bottom row for a moment, because it is the whole argument for caching in one line.
A thirty-booking day makes two and a half million calls to ask three hundred and sixty questions. Almost every call is a question that has already been answered, being answered again from scratch.
That is the moment the idea arrives on its own. We do not need a faster computer. We need to stop answering the same question twice.
Write each answer down the first time. Look it up every time after that.
Attempt 3: cache it, and watch it lie
So we take the exact function from Attempt 2 and add a dictionary. Two extra lines: look the answer up before computing it, and store the answer before returning it.
The argument that keeps changing is the booking number, so the booking number is the key. That sentence is the entire bug, and it is going to sound completely reasonable for another minute.
python
memo = {}
def best(i, free_at):
if i == len(bookings):
return 0
if i in memo: # <- look it up
return memo[i]
start, end, value = bookings[i]
without = best(i + 1, free_at)
if start < free_at:
answer = without
else:
answer = max(without, value + best(i + 1, end))
memo[i] = answer # <- write it down
return answerjava
Map<Integer, Integer> memo = new HashMap<>();
int best(int i, int freeAt) {
if (i == bookings.length) return 0;
if (memo.containsKey(i)) // <- look it up
return memo.get(i);
int start = bookings[i][0];
int end = bookings[i][1];
int value = bookings[i][2];
int without = best(i + 1, freeAt);
int answer = start < freeAt
? without
: Math.max(without, value + best(i + 1, end));
memo.put(i, answer); // <- write it down
return answer;
}c++
map<int, int> memo;
int best(int i, int freeAt) {
if (i == n) return 0;
if (memo.count(i)) // <- look it up
return memo[i];
auto [start, end, value] = bookings[i];
int without = best(i + 1, freeAt);
int answer = start < freeAt
? without
: max(without, value + best(i + 1, end));
memo[i] = answer; // <- write it down
return answer;
}javascript
const memo = new Map();
function best(i, freeAt) {
if (i === bookings.length) return 0;
if (memo.has(i)) return memo.get(i); // <- look it up
const [start, end, value] = bookings[i];
const without = best(i + 1, freeAt);
const answer = start < freeAt
? without
: Math.max(without, value + best(i + 1, end));
memo.set(i, answer); // <- write it down
return answer;
}
It gets instantly fast. It also returns 290.
Not a crash. Not an exception. A confident number, 70 minutes above anything the day can actually deliver. It is the same function that returned 220 a minute ago. We added a dictionary to it and changed nothing else.
Before reading on, it is worth answering one question for yourself. The cache has one slot per booking. What is that slot promising?
Here is what actually happens, step by step. The first path the recursion walks is the one that skips every booking. Skipping never makes the machine busy, so it arrives at booking E with the machine completely idle. E runs 15 to 18, it fits, and it is worth 50. The cache stores 50 under the key E.
Much later, a different path takes the 13-to-17 slot and then asks about E. In that path the machine is busy until 17. E starts at 15. E cannot run at all, and its true value there is 0.
The function never finds that out. It sees E in the cache, and hands back 50, because handing back the answer instead of recomputing it is the entire point of a cache.
And that 50 does not stay where it landed. Every answer built on top of it inherits the error, and one of them makes it worse.
measured
slot cached truth here inflated by
E 50 0 +50
D 110 60 +50
C 200 60 +140
B 220 150 +70
A 290 220 +70 <- the answer
What a cache key actually claims
The cache was not broken. Dictionaries work fine. The key was wrong, and it is worth being exact about what "wrong" means here, because it is not a typo.
When you write memo[i] = answer, you store two things. The value is the answer you just computed. The key is a promise about who that answer belongs to.
memo[E] = 50 says: anybody who arrives at booking E, from any path, in any situation, can have 50. That is a claim about the whole rest of the program, made by a single line, and nothing anywhere checks it.
On our day the claim was false, and the reason is one fact. Two paths reached booking E in genuinely different situations: one with the machine idle, one with it busy until 17.
They were never the same question. Storing them under the same key said they were.
Which finally answers what we started with. A subproblem is not a position in a list, and it is not a smaller copy of the input.
A subproblem is everything the rest of the run can still see. Two situations are the same subproblem when nothing that happens from here on could tell them apart.
That set of facts has a name once you are holding it. It is the state. Finding it is the entire difficulty that the three-move explanation skips over.
That is the whole argument, and it is worth watching it happen rather than only reading it.
Here are the twelve steps, from the day to the lie to the repair. Drive it yourself. Step 5 stops and asks you something, and it is worth answering before you move on.
Step by step
One machine, five bookings, and they overlap
Five teams want the one build machine today. Each request has a start, an end, and the minutes it saves. They overlap, so some have to be refused.
Take the most valuable first. That gives 220
Sort by value, accept anything that still fits. It picks C, then A, then D, for 220 minutes. Exhaustive search agrees: 220 is the best the day can do.
One team re-quotes, and the same rule loses 60
B is re-quoted from 20 to 100. Nothing else moves. The rule grabs B, which blocks A and C, and answers 160. The day is still worth 220.
So try both. Skip it, or take it, all the way down
What a choice costs is whatever it blocks, and that is in the future. So take each booking or leave it, and let the branches decide. Correct, and 36 calls for five bookings.
Both branches now ask about booking E. Same question?
One branch arrives with the machine idle. The other arrives with it booked until 17. Both are about to ask the same thing about booking E.
No. One of them cannot run E at all
E runs 15 to 18. With the machine idle it is worth 50. With the machine booked until 17 it cannot happen, so it is worth 0. Same booking, two different answers.
The cache has one slot per booking. E gets 50
The idle branch gets there first and stores its answer. The cache is keyed by booking, because that is the argument that was changing. Slot E now holds 50.
The busy branch reads slot E and is handed 50
It never recomputes, because that is what a cache is for. It is handed 50 for a booking that cannot happen in its world. No error, no warning, a number.
That 50 travels up through every answer above it
Every answer built on top of it inherits the error. D becomes 110, C becomes 200, B becomes 220, A becomes 290. Each one is stored, and each one is wrong.
The planner promises 290. The day is worth 220
It did not crash, hang or return nothing. It answered fast, confidently, and 70 minutes too high. A schedule built from that answer cannot be run.
The key was never the booking on its own
A key says: anything reaching here faces the same future. Booking E alone does not say that. Booking E plus when the machine is free does, and it answers 220.
A key is a claim that two futures are identical
Caching is the easy half and it is the half everyone teaches. The hard half is naming what the future depends on, then proving nothing else matters.
Two things in that sequence are worth pausing on, because everything after this page depends on them.
Step 6 is the moment the two branches disagree about the same booking. Step 8 is the moment the cache hands one of them the other one's answer. Everything else is bookkeeping around those two frames.
Working out the state, slowly
Let us do it properly on this problem, one question at a time. The question to ask is: what does the rest of the run actually depend on?
Stand at some point in the middle of the recursion. What do you need to be told before you could carry on correctly?
You need to know which bookings are still ahead of you. Without that you do not know what you are choosing between. We are walking the list in order, so one number covers it: the position i. Everything from i onwards is still ahead.
So i goes in.
You also need to know when the machine is next free. Without that you cannot tell which of the remaining bookings you are even allowed to take.
That is free_at. It changes independently of i: two paths can stand at the same booking with different machines behind them. So free_at goes in too.
And that is all. Nothing else about the past reaches forward. Which bookings you took, in what order, how much you have banked so far: none of it changes a single future decision. You can prove that to yourself by trying to write a line of the function that reads any of it. There is nowhere to put one.
So the state is (i, free_at), and that is the key.
python
memo = {}
def best(i, free_at):
if i == len(bookings):
return 0
if (i, free_at) in memo: # <- the whole fix
return memo[(i, free_at)]
start, end, value = bookings[i]
without = best(i + 1, free_at)
if start < free_at:
answer = without
else:
answer = max(without, value + best(i + 1, end))
memo[(i, free_at)] = answer
return answerjava
Map<String, Integer> memo = new HashMap<>();
int best(int i, int freeAt) {
if (i == bookings.length) return 0;
String key = i + ":" + freeAt; // <- the whole fix
if (memo.containsKey(key)) return memo.get(key);
int start = bookings[i][0];
int end = bookings[i][1];
int value = bookings[i][2];
int without = best(i + 1, freeAt);
int answer = start < freeAt
? without
: Math.max(without, value + best(i + 1, end));
memo.put(key, answer);
return answer;
}c++
map<pair<int, int>, int> memo;
int best(int i, int freeAt) {
if (i == n) return 0;
auto key = make_pair(i, freeAt); // <- the whole fix
if (memo.count(key)) return memo[key];
auto [start, end, value] = bookings[i];
int without = best(i + 1, freeAt);
int answer = start < freeAt
? without
: max(without, value + best(i + 1, end));
memo[key] = answer;
return answer;
}javascript
const memo = new Map();
function best(i, freeAt) {
if (i === bookings.length) return 0;
const key = `${i}:${freeAt}`; // <- the whole fix
if (memo.has(key)) return memo.get(key);
const [start, end, value] = bookings[i];
const without = best(i + 1, freeAt);
const answer = start < freeAt
? without
: Math.max(without, value + best(i + 1, end));
memo.set(key, answer);
return answer;
}
One word longer in the key. It answers 220, and it stores 13 answers to do it.
That is the whole repair. Not a smaller cache, not a cleverer one: a key that finally tells the truth about who each answer belongs to.
The state can usually be made smaller
Our key has two parts, and one of them is an awkward thing to carry: free_at is an hour, and hours are not tidy little integers starting at zero.
So look at where it comes from. free_at is never an arbitrary hour. It is always the end time of a booking we took, or the very start of the day.
Now sort the bookings by their end time instead of their start time.
Once they are in that order, "the machine is free from 13" and "we have finished with every booking that ends at or before 13" become the same sentence. Which means a position in the list can say the same thing the hour was saying. The two halves of our key have collapsed into one.
To use that, we need one small table. For each booking, we want to know: if I take this one, which booking do I jump back to?
Call it p. For booking number i, p[i] is the last booking that finishes at or before booking i starts. Everything up to and including p[i] is still available if you take i.
Let us read it off our own day. Sorted by end time the order is A, B, C, D, E, and we will number them 1 to 5.
reading p
# booking starts last one finishing by then p
1 A 09-11 09 nothing is that early 0
2 B 09-13 09 nothing is that early 0
3 C 11-13 11 A ends at 11 1
4 D 13-17 13 C ends at 13 (booking 3) 3
5 E 15-18 15 C ends at 13 (booking 3) 3
p = [0, 0, 1, 3, 3]
Read row 4 out loud, because it is the one that shows what p buys us. If we take D, we may still use anything up to booking 3. We do not have to remember an hour to know that. We just jump to 3.
And now the state is one number, so we can drop the recursion entirely and fill an array left to right.
python
# bookings sorted by end time, numbered from 1
f = [0] * (n + 1)
for i in range(1, n + 1):
f[i] = max(f[i - 1], # leave booking i out
value[i - 1] + f[p[i - 1]]) # or take it
# f = [0, 70, 70, 160, 220, 220] -> 220java
// bookings sorted by end time, numbered from 1
int[] f = new int[n + 1];
for (int i = 1; i <= n; i++) {
f[i] = Math.max(f[i - 1], // leave it out
value[i - 1] + f[p[i - 1]]); // or take it
}
// f = [0, 70, 70, 160, 220, 220] -> 220c++
// bookings sorted by end time, numbered from 1
vector<int> f(n + 1, 0);
for (int i = 1; i <= n; i++) {
f[i] = max(f[i - 1], // leave it out
value[i - 1] + f[p[i - 1]]); // or take it
}
// f = [0, 70, 70, 160, 220, 220] -> 220javascript
// bookings sorted by end time, numbered from 1
const f = [0];
for (let i = 1; i <= n; i += 1) {
f[i] = Math.max(f[i - 1], // leave it out
value[i - 1] + f[p[i - 1]]); // or take it
}
// f = [0, 70, 70, 160, 220, 220] -> 220
f[i] means "the best we can do using only the first i bookings". Each line picks the better of two things: ignore booking i and keep f[i-1], or take booking i and add the best we could do before it started, which is f[p[i]].
One pass. No recursion, no dictionary, and the same 220.
Now notice what actually happened here, because it is the part worth stealing.
The loop is four lines, and none of the difficulty was ever in those four lines. All of it was in deciding that i on its own is enough to identify a situation. And that only became true after we sorted the list.
Nothing about the problem changed. We changed the order we looked at it in, and a fact we had been carrying by hand became something we could look up.
That is a move worth having on purpose. When the state feels too big, before writing anything, ask whether some arrangement of the input would let one of the parts be worked out instead of remembered.
First decide whether dynamic programming belongs here
The booking problem was a good candidate for dynamic programming because different histories merged into the same remaining day. But recursion by itself proves nothing. Permutations branch. Binary search recurses. Neither automatically gives you reusable work.
So before hunting for a recurrence, run a merge test: can two different paths arrive at situations where every possible choice from now on, and the best answer from now on, are identical?
- Name the repeating decision. Not “what should I compute?” What is the smallest choice the problem forces on you repeatedly? Here: take this booking, or leave it.
- Describe what remains in one sentence. It must be the same kind of question on a smaller input: “the best value available from this booking onward, while the machine is free after this hour.”
- Try to merge two histories. If everything that happened earlier can be forgotten without changing legal moves or the answer from here, those histories share one subproblem.
- List what the future can still observe. Every fact that can change a legal move or future reward belongs in the state. Everything else is history.
- Count the distinct states. Memoisation saves repeated work; it does not rescue a state space with
2^ngenuinely different futures.
That separates three things people often collapse into one. A problem can have a recursive shape but no useful merging. It can have valid reusable subproblems but exponentially many of them. Or it can have a compact set of repeated futures—the situation where dynamic programming earns its keep.
| Problem | Repeating decision | What the future must know |
|---|---|---|
| House Robber | skip / take house | house index |
| Coin Change | choose next coin | amount remaining |
| 0/1 Knapsack | skip / take item | item index + capacity left |
| LCS | advance either string | index in each string |
| Word Break | choose next word | suffix start index |
| Stock with cooldown | buy / sell / wait | day + action mode |
| Visit every city | choose next city | city + visited set (2^n states) |
Do not memorise that table as seven patterns. Read each row sideways. The decision creates a smaller future. The final column contains exactly the facts that can change that future. That is how to find the DP state on a problem whose name you have never seen.
Then derive the key without guessing
Write the slow recursion first and make its return value mean the answer from this moment onward. Pass every fact the future needs as an argument. At first, put every one of those arguments in the cache key. This version may be ugly, but its meaning is inspectable.
- Write the return sentence. “
best(i, free_at)returns the maximum additional value available from bookingionward.” This keeps value already earned outside the state. - Challenge every argument with two worlds. Hold the other arguments fixed, change this one, and ask whether a future choice or answer can change. If yes, the argument belongs.
- Challenge every omitted fact the same way. If two calls share a key but that hidden fact changes their future, the key is lying.
- Only then compress. Sort, precompute, or change the traversal so a fact becomes derivable—as
free_atbecamep[i]here. Prove the smaller state; never obtain it by deleting a field.
A shorter key matches more often. More matches means more cache hits, so deleting a field can look like an optimisation. It is only an optimisation if the two futures remain identical. Otherwise it is the bug on this page.
How to catch this in a minute instead of in production
There is one habit that would have caught our 290 immediately, and it costs nothing.
Keep the slow version. The plain recursion from Attempt 2, with no cache in it, is unbearably slow and completely correct. Do not delete it when you write the fast one.
A function you trust completely is worth more than a fast one. It gives you something to compare against, so you never have to reason about whether the fast version is right. You can just check.
So: generate small inputs, five or six bookings each, a few hundred of them. Run both functions on every one. Assert that they return the same number.
That is four lines of test. Our 290 would have shown up on the very first day of five bookings, on a laptop, before any of this reached a schedule somebody tried to run.
Why it is called dynamic programming
Notice that nothing above needed the phrase. We found a decision, described what was left, worked out what had to be remembered, and cached on exactly that. The name is a label for something you are already holding.
It is also, by the account of the man who coined it, mostly a disguise. Richard Bellman was working at RAND in the early 1950s, under a Secretary of Defense he describes as having "a pathological fear and hatred of the word research".
So if the phrase has never told you anything, that is not a gap in your understanding. It was built to say nothing.
The thing it names is a decision, a leftover, and a list of what has to be remembered.
The idea worth keeping
A cache key is not storage. It is a claim that two situations have the same future.
And it is the only claim in the whole technique that nothing checks for you. The compiler will not. The tests usually will not, because the function is fast, it returns a number of the right size, and on most days it returns the right one.
"Two situations" means two moments in the run where the function is called. Ours were: standing at booking E with the machine idle, and standing at booking E with the machine busy until 17.
Same key. Completely different futures. One of them could still run E and one of them could not, and the cache had already decided they were the same.
So on the next problem, change the question you are asking yourself.
Not "what should I compute here". That question searches the code, and the code is usually fine. Ask instead: what would have to be identical about two situations for them to have the same answer? That question searches the situations, and the recurrence has been sitting in there the whole time.
We have barely scratched the surface of what a state can be. It can be two positions walking two strings, a budget you have left, a balance you are carrying, or a single flag saying whether you are currently holding something.
The question is identical every time. After a while you stop hunting for the pattern and start hunting for the state.