Skip to content
Official PYQ · 2005

GATE CS 2005 Q81a — Asymptotic Worst Case Time and Space Complexity

Explain with AI
double foo(int n)
{
    int i;
    double sum;
    if(n == 0)
    {
        return 1.0;
    }
    else
    {
        sum = 0.0;
        for(i = 0; i < n; i++)
        {
            sum += foo(i);
        }
        return sum;
    }
}

The space complexity of the above code is?

Choose one option
View worked solution

Answer: B

The space complexity of a recursive function is determined by the maximum depth of the recursion stack (i.e., the maximum number of active stack frames at any point during execution).

Let's analyze the execution of foo(n):

  • When foo(n) is called, it executes a loop from i = 0 to n - 1, making sequential recursive calls to foo(i).
  • Because these calls are sequential, the space allocated for foo(i) is deallocated (popped from the stack) as soon as it returns, before the next call foo(i + 1) begins.
  • The maximum depth of the recursion stack occurs during the deepest chain of active recursive calls, which happens when the loop reaches its last iteration at each level:
foo(n)⟶foo(n−1)⟶foo(n−2)⟶⋯⟶foo(0)\text{foo}(n) \longrightarrow \text{foo}(n-1) \longrightarrow \text{foo}(n-2) \longrightarrow \dots \longrightarrow \text{foo}(0)

At this peak, there are n+1n + 1 active stack frames on the call stack.

Since each stack frame requires a constant amount of memory, O(1)O(1), to store local variables (i, sum) and the parameter n, the maximum space complexity is:

Space Complexity=O(n)\text{Space Complexity} = O(n)

Hence, the correct option is B.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions