1
public int fib(int n) {
if (n == 0) return 0; 
if (n == 1) return 1; 
return fib(n-1) + fib(n-2);
}

I am confused why the space complexity of the above code is O(n). Now, I know the depth of recursion is n, that is, the height of the tree.

There are no temporary variables or final result variables created. Is the space complexity here computed from the function call stack?

Abhishek Bhatia
  • 9,404
  • 26
  • 87
  • 142

1 Answers1

2

Yes, the space complexity in this case depends on the space used in call stack, that depends on the number of active function call (function called but not finished execution).

If you observe the last statement

return fib(n-1) + fib(n-2)

When fib(n-1) is calculated O(n) space is used. Once fib(n-1) completes execution stack space can be reused by fib(n-2).

So, in this case, the number of active stack frame at any time for a call to fib(n) is O(n), hence the space complexity is O(n).

It is worth noting that the time complexity, however, is exponential.

Abhijith Asokan
  • 1,865
  • 10
  • 14