Watch how memoization caches recursive Fibonacci calls, eliminating redundant computation and reducing complexity from O(2ⁿ) to O(n).
About this algorithm
Memoization makes recursive Fibonacci fast: it saves each fib(n) the first time it is worked out and returns the saved answer on every later call, so the work drops from exponential to O(n). The Fibonacci numbers start 0, 1, and each one after is the sum of the two before it. Written as plain recursion, fib(n) calls fib(n - 1) and fib(n - 2), and the same calls repeat so often that the work grows exponentially. It is the simplest way to see what dynamic programming saves.
Reach for memoization when a recursive solution keeps asking the same smaller questions, and writing the recursion is the clearest way to think about the problem. It works well when only some subproblems are ever needed, since it computes only the ones the recursion reaches. Bottom-up tabulation, as on the coin change and knapsack pages, fills every subproblem in a loop and avoids deep recursion, which matters in languages with a small call stack such as Python. For Fibonacci itself, keeping just the last two values in a loop is fastest and uses constant memory.
If n is 0 or 1, return n. These calls never touch the memo.
If memo[n] already holds a value, return it straight away. This is a cache hit, and the whole subtree of calls below it is skipped.
Call fib(n - 1), then fib(n - 2). Because the first call fills the memo on its way back up, the second call finds its answer already saved.
Store the sum in memo[n], then return it. Every value from 2 up to n is computed exactly once.
The page opens on n = 7. The calls run straight down the left side: fib(7), fib(6), fib(5), fib(4), fib(3), fib(2), then the base cases fib(1) = 1 and fib(0) = 0. On the way back up, memo[2] = 1, then fib(3) calls fib(1) = 1 and saves memo[3] = 2. Now every right-hand call is a hit: fib(4) reads memo[2], fib(5) reads memo[3], fib(6) reads memo[4] and fib(7) reads memo[5]. The memo fills as 1, 2, 3, 5, 8, 13, and fib(7) = 13. That took 13 calls. Plain recursion makes 41 calls for the same answer, and at n = 10, the top of the slider, it is 19 calls against 177.
With the memo, fib(n) makes 2n - 1 calls. The left spine, fib(n) down to fib(1), is n calls, and each of fib(2) to fib(n) makes one more call on its right, which is either a base case or a memo hit. Without it, the count follows the Fibonacci numbers themselves, 2 × fib(n + 1) - 1, which grows by about 1.6 times for each step in n.
Time: each value from 2 to n is computed once and every other call returns at once from the memo or a base case, so there are 2n - 1 calls. Space: the memo holds n + 1 slots and the recursion goes n calls deep before the first value returns.