Lesson 11: Dynamic Programming — Memoisation
In Lesson 3 you met the naive recursive Fibonacci, which takes exponential time because it recomputes the same values over and over. For fib(5) it computes fib(2) three times; for fib(40) it computes fib(2) tens of millions of times. Dynamic programming (DP) fixes this with one idea: remember the answer to each subproblem the first time you solve it, and reuse it afterwards. That memory is called memoisation, and it turns the exponential Fibonacci into a linear one — each value from 0 to n is computed exactly once.
Memoisation is recursion plus a dictionary. Before computing fib(n), you check whether the answer is already in the dictionary; if it is, you return it immediately. If not, you compute it the usual way, store it, and then return it. Nothing else about the function changes. The example below shows the transformation, and the difference in speed is dramatic: the naive version struggles with n = 40, while the memoised version handles n = 900 easily — though Python's default recursion limit of 1,000 frames means very deep recursion still needs care.
def fib_naive(n):
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
def fib_memo(n, memo=None):
if memo is None:
memo = {}
if n in memo:
return memo[n]
if n < 2:
result = n
else:
result = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
memo[n] = result
return result
print(fib_memo(40)) # 102334155 — instant, where the naive version crawls
When does dynamic programming apply?
Dynamic programming works when a problem has two properties. The first is overlapping subproblems: the same smaller problem appears again and again, so remembering answers actually helps. The second is optimal substructure: the best answer to the whole problem can be built from the best answers to its parts. Fibonacci has both — fib(n) is built from fib(n-1) and fib(n-2), and those subproblems overlap heavily. Sorting a list does not have overlapping subproblems in the same way, which is why DP is not the tool for sorting.
There is also a one-line shortcut worth knowing. Python's standard library provides functools.lru_cache, a decorator that memoises any function automatically — you saw it mentioned in the decorators unit of the Python course. Adding @lru_cache(maxsize=None) above the naive Fibonacci makes it fast with no other change. It is a wonderful tool for contests, but learn the manual version first: understanding what the cache holds is what lets you reason about a DP solution's time and space, and the manual version is what you will debug when the decorator hides the details.
Going further
The Fibonacci example hides a subtle point: the overlapping subproblems are not just a curiosity, they are the whole reason memoisation helps. Consider computing the number of paths through a grid, moving only right or down. The number of paths to a cell is the sum of the paths to the cell above and the cell to the left — and those two subproblems themselves share subproblems, because the paths to neighbouring cells overlap heavily. Without memory, the recursion recomputes the same cells exponentially many times; with memory, each cell is computed once. The grid makes the overlap visible in a way the Fibonacci numbers do not.
A practical detail: the lru_cache decorator takes a maxsize argument, and passing None means the cache is unbounded — it never throws anything away. For a contest solution that is usually what you want, because the number of distinct states is the thing you are counting anyway. But in a long-running program, an unbounded cache is a memory leak in disguise: every distinct call is remembered forever. The default maxsize of 128 keeps only the most recently used entries, which is a sensible balance when the same arguments recur and the old ones will not be needed again.
A good way to feel the power of memoisation is to time the two Fibonacci versions yourself. Run the naive version with n = 30 and note how long it takes, then try n = 35 and watch the time grow by roughly tenfold, because each extra step multiplies the work by about 1.6. Then run the memoised version with n = 900 and watch it return instantly. The exact timings will depend on your machine, so treat them as an illustration rather than a measurement, but the contrast is the lesson: the same problem, the same recurrence, and a difference of many orders of magnitude from one dictionary.
Key Terms
- Dynamic programming (DP)
- Solving a problem by breaking it into subproblems, solving each once, and reusing the answers.
- Memoisation
- Storing the result of each subproblem the first time it is computed, and reusing it later.
- Overlapping subproblems
- The same smaller problem appearing many times in a recursion, so remembering answers pays off.
- Optimal substructure
- The best answer to a problem being built from the best answers to its subproblems.
- lru_cache
- A standard-library decorator that memoises a function automatically.
- Top-down DP
- Dynamic programming written as recursion plus memoisation, solving subproblems as needed.
- State
- The inputs that identify one subproblem, such as n in fib(n); the memo is keyed by state.
Discussion Questions
- Why is the naive Fibonacci exponential while the memoised version is linear? Count how many distinct values of fib(n) exist for a given n.
- What two properties must a problem have for dynamic programming to help? Give an example of a problem that has neither.
- When would you use @lru_cache, and when would you write the memo dictionary by hand?
Practice Questions
- How many times does the naive
fib(5)computefib(2)? - What does the memo dictionary hold, and what is it keyed by?
- What is the time complexity of
fib_memo(n)? - Name the two properties a problem needs for DP to apply.
- What does
@lru_cache(maxsize=None)do to a function?
Show answers
- Three times. The recursion tree recomputes the same subproblems; memoisation computes each once.
- It holds already-computed Fibonacci values, keyed by n. Checking n in memo before computing is what avoids the repeated work.
- O(n). Each value from 0 to n is computed once, and each computation does O(1) work beyond its recursive calls.
- Overlapping subproblems and optimal substructure. Without overlap, remembering answers saves nothing; without optimal substructure, subproblem answers cannot build the whole answer.
- It memoises it automatically, with an unbounded cache. Repeated calls with the same arguments return the stored result instead of recomputing.