Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: The recursive function below counts calls. How many times is f called for f(5)?

Problem: The recursive function below counts calls. How many times is f called for f(5)?
calls = 0
def f(n):
    global calls
    calls += 1
    if n <= 1: return n
    return f(n - 1) + f(n - 2)
print(f(5), calls)
What is printed?
  1. A. 5 9
  2. B. 5 15
  3. C. 8 15
  4. D. 5 16

Correct answer: B. 5 15

C(n) = 1 + C(n − 1) + C(n − 2), C(0) = C(1) = 1: 1, 1, 3, 5, 9, 15. fib(5) = 5. The call count grows like φⁿ, which is why memoisation (n + 1 calls) matters.

More Coding Interview Problems questions

Exams that ask this topic