ProgrammingHardAmazon OA · TCS Digital

What is the extra space (memory) used by the following recursive pseudocode as a function of n, counting the call stack?

What is the extra space (memory) used by the following recursive pseudocode as a function of n, counting the call stack?
Function fib(Integer n)
    if (n <= 1)
        return n
    end if
    return fib(n - 1) + fib(n - 2)
End Function
  1. A. O(2ⁿ)
  2. B. O(1)
  3. C. O(n)
  4. D. O(log n)

Correct answer: C. O(n)

Although about 2ⁿ calls are made in total, at any moment only one chain of calls is active, and the deepest chain is fib(n) → fib(n − 1) → … → fib(1), of length n. So the stack uses O(n) space; the TIME is exponential.

More Pseudocode and Code Tracing questions

Exams that ask this topic