Data Structures & AlgorithmsVery hardGATE CS · TCS NQT · Product Company SDE

What is the space complexity of this recursive factorial function, as a function of n (ignoring the final integer result size)?

What is the space complexity of this recursive factorial function, as a function of n (ignoring the final integer result size)?
int fact(int n) {
  if (n == 0) return 1;
  return n * fact(n - 1);
}
  1. A. O(1)
  2. B. O(n)
  3. C. O(log n)
  4. D. O(n^2)

Correct answer: B. O(n)

Each call stays on the call stack until its recursive call returns, so the stack depth grows to n before unwinding: O(n) space, not O(1).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic