Turn exponential O(2ⁿ) recursive Fibonacci into O(n) with memoization using a dict or functools.lru_cache. See the difference live in Python.
The problem
Return the n-th Fibonacci number (fib(0) = 0, fib(1) = 1) using recursion with memoization. It must handle n = 300 instantly.
Examples
Example 1
Input
fib(10)
Expected output
55
Example 2
Input
fib(0)
Expected output
0
+ 3 hidden tests on Submit — must be memoized.
Edge cases to ask about
- n = 0 and 1
- Large n (300)
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Plain recursion | O(2ⁿ) | O(n) | fib(n−2) is recomputed inside fib(n−1) over and over. |
| Memoized recursion | O(n) | O(n) | Each fib(k) is computed once. |
| bestTwo variables, bottom-up | O(n) | O(1) | a, b = b, a + b. |
Walkthrough of the optimal approach (try it yourself first)
Plain recursion recomputes the same subproblems exponentially many times (O(2ⁿ)). A memo dict stores fib(k) the first time; every later request is O(1), so total work becomes O(n).
Note the memo=None default: a mutable default memo={} would work here but is the trap from question 66. @functools.lru_cache(maxsize=None) is the idiomatic version.
Complexity: O(n) time, O(n) space. With the memo every fib(k) for k ≤ n is computed exactly once; the memo and the call stack each hold O(n).
Reveal the reference solution
def fib(n, memo=None): if memo is None: memo = {} if n < 2: return n if n not in memo: memo[n] = fib(n - 1, memo) + fib(n - 2, memo) return memo[n]
Follow-ups interviewers ask
- Bottom-up with O(1) space.
- O(log n) with matrix exponentiation.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Fibonacci With Memoization in Python?
The optimal solution runs in O(n) time and O(n) auxiliary space. With the memo every fib(k) for k ≤ n is computed exactly once; the memo and the call stack each hold O(n).
What is the brute-force approach, and how do you optimise it?
Plain recursion: O(2ⁿ) time, O(n) space. fib(n−2) is recomputed inside fib(n−1) over and over. Memoized recursion: O(n) time, O(n) space. Each fib(k) is computed once. Two variables, bottom-up: O(n) time, O(1) space. a, b = b, a + b.
What follow-up questions do interviewers ask about Fibonacci With Memoization?
Bottom-up with O(1) space. O(log n) with matrix exponentiation.
