0

I didn't get how its O(n^2)...given in image attached according to me it should be O(n)

array[n];
array[0] = 1;
array[1] = 1;
for i = 2 to i = n:
   array[i] = array[i-1] + array[i-2]
return array[n]

Fibonacci series

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • this is not C++, if you use a pseudo language remove the tag C++ – bruno May 08 '20 at 20:33
  • 1
    Where did you get that attached image from? And yes, It's not correct. – NathanOliver May 08 '20 at 20:34
  • fibo(0) is 0, not 1. The complexity is O(n) because this is the complexity of the loop. In the picture may be the complexity of O(n²) is about the recursive definition where f(n) = f(n-1)+f(n-2) even the formula is wrong ? – bruno May 08 '20 at 20:40
  • @bruno But the image uses a loop, not a recursive call. – NathanOliver May 08 '20 at 20:43
  • 1
    Creating and accessing an array should be `O(1)`, not `O(n)` unless, `F` is no array. Maybe it's a linked list that for some reason uses indices and iterates through the whole list to reach a specific index? – Lukas-T May 08 '20 at 20:45
  • is a typo, picture wanted to say O(2*n) but I disagree on O(N) to create the array if it is not initialized (and there is no reason to initialize it), and fo course when they say O(N) to do `array[i] = array[i-1] + array[i-2]` – bruno May 08 '20 at 20:45
  • This image is from a coursera lecture about algorithms – technical_geek May 09 '20 at 15:12

1 Answers1

0

The picture you've linked is incorrect. Each iteration of that loop takes time O(1) to execute, and it runs O(n) times, so the cost of that loop is O(n). It looks like the slide accidentally multiplied the O(n) total cost of the loop by the O(n) number of iterations to incorrectly get an O(n2) term.

Your analysis is correct - this code does run in time O(n).

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065