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?
GATE CSE 2005Algorithms › Growth of Functions & Complexity AnalysisVerified
(B) O ( n ) O(n) O ( n )
Analyze the recursion stack depth. Each recursive call foo(i) is made sequentially inside a for loop, so at any moment only one call chain is active. The maximum depth occurs when foo(n) calls foo(n-1), which calls foo(n-2), and so on down to foo(0). Thus the stack holds O(n) frames, each using O(1) local variables.
The recursion in foo(n) calls foo(i) for i = 0..n-1 one after another. The deepest call stack occurs when foo(n) calls foo(n-1), which calls foo(n-2), and so on down to foo(0). This gives n+1 active stack frames, each with O(1) local variables. Therefore the space complexity is O(n), matching option B.
Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.