简体   繁体   中英

Space Complexity and Auxilary space for iterative code below>>>>

int fib(int n){   // let n = 4;
  int f[n+1];     // array length becomes 5
  f[0] = 0;         
  f[1] = 1;
  for(int i = 2 ; i <= n ; i++ ){
     f[i] = f[i-1] + f[i-2];
  }
  return f[n];    
}

Now, The Time Complexity of this program is coming out to be O(n) or Theta(n) But, what will be the Space Complexity and Auxilary space?

For results on internet it showing SC = theta(n) and aux space also thetha(n) but how??

if we see that the space created by us for fibonacci series is (n+1) so by removing constant the Aux space becomes theta(n) but the space Complexity (by my calculation) is thetha(1) because this program taking an integer as input and giving back an integer as output so it come up to be constant ie Theta(1), but every where it is theta(n) How? Please Explain>>>

Visualization solution for this problem is it correct??

With that array:

int[] f = new int[n + 1];

You have Space Complexity O(n) .

But you need to keep only the last two elements in memory:

int fib(int n){   // let n = 4;
    int a = 0;
    int b = 1;       
    int c = a + b;  
    for (int i = 2 ; i <= n; i++) {
        a = b;
        b = c;
        c = a + b;
    }
    return c;    
}

In that algorithm the space complexity is O(1) .

Actually same non-trivial space and time complexity is suspicious.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM