Sit down, have your tea, and let us look at the Fibonacci function you wrote in your first year. Each number is the sum of the previous two, so you wrote a function that calls itself for n-1 and n-2. It is short, it is elegant, and it is quietly terrible. Understanding exactly why it is terrible is most of what “dynamic programming” means.
Count the calls, not the answer
Ask for the 5th Fibonacci number. The function asks for the 4th and the 3rd. The 4th asks for the 3rd and the 2nd. Notice that the 3rd has now been requested twice, from two different places, and each request will redo all its own work from scratch. Nobody is remembering anything.
Let me give you actual numbers, which I checked by running the function with a counter. Computing the 10th number takes 177 calls. The 20th takes 21,891. The 30th takes 2,692,537. Each step of 10 multiplies the work by roughly a hundred. By the 40th number you are past 330 million calls, and your laptop fan starts to sound like a ceiling fan in May in Madurai. The function is not slow because the arithmetic is hard; each call does one addition. It is slow because it solves the same tiny problem again and again. The running time grows exponentially, roughly by a factor of 1.6 for every step in n.
First fix: write the answer down
The cheapest repair is to keep a notebook. Before computing the value for n, look in the notebook (a dictionary or an array). If it is there, return it. If not, compute it the usual recursive way, write it in the notebook, then return it. This is called memoisation. The word comes from “memo”, as in a note to yourself, and has nothing to do with memory management.
Now trace the 5th number again. The first time anyone needs the 3rd, it is computed and stored. The second time, it is a lookup. Each value from 0 to n is computed exactly once, so the work is about n steps instead of 2.69 million for n = 30. Same code shape, a few extra lines, an astronomical difference.
Python gives you this nearly free with functools.lru_cache on the function. Java and JavaScript need a map you manage yourself. One catch for later: this version still recurses 30, 500 or 5,000 levels deep, and many languages will refuse past a few thousand frames. Python’s default limit is about 1,000.
Second fix: stop recursing altogether
Look at what memoisation taught you. To compute value n you only ever need the two values below it. So why wait for recursion to find them? Start at 0 and 1, and walk upwards, filling the notebook in order. When you reach n, you are done. No recursion, no stack depth problem.
This bottom-up version is what most textbooks call dynamic programming (the name is historical and not very helpful). Since each step needs only the previous two values, you can even throw the notebook away and keep two variables. Memory drops from n to a constant. That last trick is optional, but it shows what the technique is really about: understanding which earlier answers a later answer depends on.
A problem where greedy fails
Fibonacci is a toy. Here is one where the technique earns its keep. A canteen machine in Coimbatore issues change using coins of ₹1, ₹5, ₹6 and ₹9 only (illustrative, no such set exists in circulation). What is the fewest number of coins that makes ₹11?
Your instinct says take the biggest coin first: 9, then 1, then 1. That is three coins. But 5 and 6 make 11 in two. Greedy fails here because grabbing the biggest coin closes off a better combination.
So define a small question: what is the fewest coins for amount a? The answer for any amount is one coin plus the best answer among the amounts you could have come from (a-1, a-5, a-6, a-9, whichever are not negative). Fill a table from 0 upwards:
| Amount | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Fewest coins | 0 | 1 | 2 | 3 | 4 | 1 | 1 | 2 | 3 | 1 | 2 | 2 |
Check ₹10: from ₹9 plus one coin of 1 gives 1+1 = 2. Check ₹11: from ₹5 (1 coin) plus a ₹6 coin gives 2. Twelve cells, each looking at four neighbours, and the answer is certain. A brute-force search over all combinations would grow explosively as the amount rose.
How to recognise the pattern
Two properties need to hold, and both are worth checking before you reach for a table.
- Overlapping sub-problems. The same smaller question comes up repeatedly. If every sub-problem is different, remembering answers saves nothing. That is why merge sort, which splits into fresh halves, does not need a notebook.
- Optimal substructure. The best answer to the big problem can be assembled from best answers to smaller ones. Shortest path in a graph has this; “longest path without repeating a node” does not.
Typical homes for this: edit distance between two strings, the knapsack problem, counting paths through a grid, splitting a rod for maximum price, and spell-check suggestions.
Top-down or bottom-up?
Both give the same running time, so choose on practical grounds. Memoised recursion is easier to write because you simply transcribe the definition, and it computes only the sub-problems actually needed. Bottom-up avoids deep recursion, has less call overhead, and makes it easy to drop old rows to save memory. My own preference when the recursion is natural: write top-down first, get it correct, and convert only if depth or speed forces you.
One honest limit. If the number of distinct sub-problems itself is huge (say, a state defined by three numbers each up to 10,000), the table will not fit in memory, and no amount of cleverness with caching changes that. At that point you are looking for a different formulation or an approximation.
Figures and names in the examples are illustrative.
Leave a Reply