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?- A. 89 10
- B. 177 11
- C. 1024 11
- 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
- What is the time complexity of this loop? python for i in range(1, n + 1): j = 1 while j j <= i: j += 1
- What is the solution of T(n) = 2T(√n) + log n?
- A hash table with separate chaining and simple uniform hashing has n keys in m buckets (load factor α = n/m). What is the expected time of…
- An LRU cache must support get and put in O(1). Which design achieves this?
- Edge case: identity versus equality in Python. python a = [1, 2]; b = [1, 2]; c = a print(a == b, a is b, a is c, [] is []) What is printed?
- Edge case: chained comparisons and booleans as integers in Python. python print(1 < 2 > 1.5, (1 < 2) > 1.5, True + True, 3 > 2 == 2) What…