ProgrammingHardAccenture · Cognizant pattern

What is the space complexity (auxiliary stack space) of the following recursive factorial function for input n?

What is the space complexity (auxiliary stack space) of the following recursive factorial function for input n?
Function fact(Integer n)
    if (n <= 1)
        return 1
    end if
    return n * fact(n - 1)
End Function
  1. A. O(1)
  2. B. O(log n)
  3. C. O(n)
  4. D. O(n^2)

Correct answer: C. O(n)

Each recursive call adds one more frame to the call stack before any of them return (since the multiplication happens after the recursive call completes), so the maximum stack depth grows linearly with n, giving O(n) auxiliary space.

More Pseudocode and Code Tracing questions

Exams that ask this topic