Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the space complexity of this code?

Tags:

c

algorithm

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.

like image 390
chris Avatar asked Dec 31 '16 21:12

chris


People also ask

What is space complexity and how it is calculated?

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.

What is space complexity in Python?

The space complexity is basically the amount of memory space required to solve a problem in relation to the input size.

What is space complexity O 1?

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.


1 Answers

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.

like image 76
Barmar Avatar answered Oct 03 '22 06:10

Barmar