Fibonacci memoization
- Algorithms course
- Advanced
- Lesson 2/56
- 4 min
Speed up recursive Fibonacci with memoization.
Fibonacci memoization
Speed up recursive Fibonacci with memoization: store each n's result in a dictionary.
Compute and store on first call; return the stored value on later calls.
This small change drops fibonacci from Θ(2^n) to Θ(n); a big difference.
Dictionary check
First check if n is in the cache. If yes return directly; else compute and store.
This ensures each subproblem is solved only once.
The cache check is the heart of memoization; it must be implemented correctly.
Practice Fibonacci memo
Write fib_memo(n, memo). Recursive Fibonacci with memoization. Print 55 with print(fib_memo(10, {})).
Starter code
def fib_memo(n, memo):
# Fibonacci memoSample solution
def fib_memo(n, memo):
# Fibonacci memo
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
return memo[n]
print(fib_memo(10, {}))Expected output
55
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Cache check
if n in ____:
if n in memo:
Explanation: memo is right.
2 Fibonacci memoization: match the terms
| Term | Meaning |
|---|---|
memo |
Cache |
dict |
Dictionary |
n |
Parameter |
return |
Return |
3 What is Fibonacci memoization's complexity?
- Θ(log n)
- Θ(2^n)
- Θ(n^2)
- Θ(n) Correct answer
Explanation: Θ(n).