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 and stores the value of , as and when they are computed. With this modification the time complexity for function is significantly reduced. The space complexity of the modified function would be:
View worked solution
Answer: B
The question describes a memoization (dynamic programming) approach to optimize the recursive function foo().
1. Memoization Table Space
To store the computed values of for , we need a table (such as an array) of size . This requires:
2. Recursion Stack Space
To compute , the function recursively calls , which in turn calls , and so on, down to the base case .
- The maximum depth of the recursion stack is .
- Therefore, the space required by the call stack is .
Conclusion
Combining the space required for the memoization table and the recursion stack:
Hence, the correct option is B.
Free practice · Your answers on this page are not saved.
