GATE CS 2005 · Asymptotic Analysis & Recurrences

MCQ · 1 mark · Problem PROG-DIVC-0146

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;
    }
}
Suppose we modify the above function foo() and store the values of foo(i), \(0 \le i \lt n\), as and when they are computed. With this modification, the time complexity for function foo() is significantly reduced. The space complexity of the modified function would be:
  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{stored values} + \text{recursion stack}}\]With the values stored, each of foo(0), ..., foo(n-1) is kept once: a table of \(n\) values, \(O(n)\).The recursion stack is still at most \(n+1\) calls deep (foo(n) calls foo(n-1), which calls foo(n-2), and so on), also \(O(n)\).Total space \(=O(n)\).Answer: B

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