edited by
10,965 views
35 votes
35 votes
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 stores the value of $foo(i) \ 0 \leq i < 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. $O(1)$
  2. $O(n)$
  3. $O(n^2)$
  4. $n!$
edited by

5 Answers

1 votes
1 votes

Requires N units for a plus extra space for n, i and sum, so it's O(N).

Because in this question the value of function foo (i)  vary between 0 to n so its takes total space n so 

Sum = sum + foo(i) 

         = O(1) + O (N)

         = O(N)

so overall space complexity will be O(N)

Answer:

Related questions

53 votes
53 votes
5 answers
1
Kathleen asked Sep 22, 2014
19,242 views
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 a...
13 votes
13 votes
3 answers
3
Kathleen asked Sep 22, 2014
12,448 views
A common property of logic programming languages and functional languages is:both are procedural languages both are based on $\lambda$-calculusboth are declarativeboth us...