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?- A. 5 9
- B. 5 15
- C. 8 15
- 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
- Problem: Compute xⁿ by fast exponentiation (recursive squaring) and count multiplications. python mults = 0 def power(x, n): global mults…
- Problem: Generate the letter combinations a phone keypad number can represent and report how many there are. python from itertools import…
- Problem: Count set bits for each number 0..n using DP on the lowest bit. python def bits(n): r = [0] (n + 1) for i in range(1, n + 1)…
- Problem: Check whether a number is a power of two and isolate its lowest set bit. python print("; ".join(f"{x > 0 and x & (x - 1) == 0} {x…
- Problem: Every value appears three times except one, which appears once. Find it with O(1) extra space. python def single(a): ones = twos…
- Problem: Two values appear once and every other value twice. Find both (smaller first). python def twosingle(a): x = 0 for v in a: x ^= v…