Data Structures & AlgorithmsVery hardAmazon · Microsoft OA

Problem: Count the calls made by naive recursive Fibonacci versus a memoised version for n = 10.

Problem: Count the calls made by naive recursive Fibonacci versus a memoised version for n = 10.
from functools import lru_cache
naive = 0
def fib(n):
    global naive
    naive += 1
    return n if n < 2 else fib(n - 1) + fib(n - 2)
memo_calls = 0
@lru_cache(None)
def mfib(n):
    global memo_calls
    memo_calls += 1
    return n if n < 2 else mfib(n - 1) + mfib(n - 2)
fib(10); mfib(10)
print(naive, memo_calls)
What is printed?
  1. A. 89 10
  2. B. 177 11
  3. C. 1024 11
  4. D. 55 11

Correct answer: B. 177 11

The naive call count satisfies C(n) = C(n−1) + C(n−2) + 1 with C(0) = C(1) = 1, so C(n) = 2F(n+1) − 1 = 2 × 89 − 1 = 177. With memoisation each n from 0 to 10 is computed once: 11 function bodies run.

More Coding Interview Problems questions

Exams that ask this topic