int f(int n)
{
if (n <= 1)
{
return 1;
}
return f(n - 1) + f(n - 1);
}
I know that the time complexity is O(2^n)
and I understand why.
But I don't understand why the space complexity is O(n)
.
I was told that it's because at any given time there are only n
nodes, but it doesn't make sense to me.
Space complexity is the total amount of memory space used by an algorithm/program including the space of input values for execution. So to find space-complexity, it is enough to calculate the space occupied by the variables used in an algorithm/program.
The space complexity is basically the amount of memory space required to solve a problem in relation to the input size.
o(1) space complexity means that the amount of memory that you use is constant and does not depends on the data that it is processing, more information here.
Because the second f(n-1)
can't run until the first one completes (or vice versa -- it's the same either way). The first call will recurse n
times, then all those will return, so that will push a total of n
stack frames. Then the second call will do the same thing.
So it never gets more than n
levels deep in the recursion, and that's the only contributor to space complexity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With