GATE CS 2005 · Asymptotic Analysis & Recurrences

MCQ · 1 mark · Problem PROG-DIVC-0147

Consider the following C function:
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 function is:
  1. A
    O(1)
  2. B
    O(n)
  3. C
    O(n!)
  4. D
    O(\(n^{n}\))

Solve it on GATE DA practice →More Searching & Sorting Algorithms problems

Show the worked solution\[\boxed{\text{space} = (\text{maximum recursion depth}) \times O(1)}\]Each call uses \(O(1)\) space (i and sum) and has only one child call active at a time. The deepest chain is foo(n), foo(n-1), ..., foo(0), so at most \(n+1\) calls are on the stack together.Space \(=O(n)\). (The time is exponential: foo(n) makes \(2^{n}\) calls in all. The space is still linear.)Answer: B

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com