Memoization: recursion that remembers
Write the natural first, then cache each result. time often drops to polynomial with one decorator.
The idea
Many recursive solutions recompute the same inputs again and again. recursion calls fib(3) many times inside fib(6). Storing each answer the first time turns repeated calls into lookups.
(memo) is often easier to get right than tables: write the recursion, add a cache, done.
Worked example
Coin Change: fewest coins for 11 with coins [1, 2, 5]
- best(11) = 1 + min(best(10), best(9), best(6))
- Without a cache, best(5) is recomputed many times; with one, each amount 0..11 is solved once.
- Answer 3 (5 + 5 + 1).
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
ways(5), 1 or 2 steps at a time
memo
{ } empty — nothing seen yetSolution · Python
from functools import cache def coin_change(coins, amount):@cachedef best(rest):if rest == 0:return 0if rest < 0:return float("inf")return 1 + min(best(rest - c) for c in coins) answer = best(amount)return -1 if answer == float("inf") else answerStep 1 of 8
ways(n) = ways(n − 1) + ways(n − 2). Plain recursion recomputes the same small cases again and again. A memo stores each answer the first time, so it's never computed twice.
O(amount × coins) time, O(amount) space for the cache.
How to spot it
- Your recursion has (the same arguments repeat).
Common mistakes
- Caching on arguments like lists (they aren't hashable).
- Deep recursion on large inputs: Python's default limit is about 1000 frames.
Practise the ideas first
One small exercise per idea, right in the editor, before the problems below.
Practise it
Go further
Up next for you · Beginner
“Have I seen this?” is a set →