Counting recursive calls — Aptitude Question
Counting recursive calls: The naive recursion fib(n) = fib(n − 1) + fib(n − 2), with fib(0) and fib(1) returned… Answer and worked solution on CodeKairo.
- Topic: Data Structures & Algorithms
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 105 seconds
Question
The naive recursion fib(n) = fib(n − 1) + fib(n − 2), with fib(0) and fib(1) returned directly, is used to compute fib(5). How many calls to fib are made in total, including the first one?
Options
- 8
- 9
- 15
- 25
Show the answer and the worked solution
Correct answer: C. 15
Worked solution
- Let T(n) be the total number of calls. T(0) = T(1) = 1, since those return without recursing.
- Otherwise T(n) = 1 + T(n − 1) + T(n − 2), counting the call itself.
- T(2) = 1 + 1 + 1 = 3 and T(3) = 1 + 3 + 1 = 5.
- T(4) = 1 + 5 + 3 = 9.
- T(5) = 1 + 9 + 5 = 15.
Answer: 15.
The idea
The call count is 2·fib(n + 1) − 1, so it grows exponentially — the standard argument for memoising the recursion or rewriting it as a loop.
Shortcut. Every non-base call has exactly two children, so calls = 2 × leaves − 1; the leaves are the fib(1) and fib(0) calls, fib(6) = 8 of them, giving 15.
Common trap. 8 counts only the base-case calls at the leaves of the call tree and forgets the 7 internal calls that spawned them.
All Data Structures & Algorithms questions · placement mock tests