Search code examples
javaalgorithmasymptotic-complexity

Calculating the BigO for a code


I read an article online. The BigO for the below code as per my understanding should be O(n). As the loop runs n times. But the correct answer in the articles shows as O(1). With the explanation

The code declares exactly 4 variables: i, j, k and t. 4 = constant = O(1).

How?

As per my understanding, the loop runs n times hence O(n)

int fibonacci(int n)
{
   int i = 0, j = 1, k, t;
   for (k = 1; k <= n; ++k)
   {
     t = i + j;
     i = j;
     j = t;
   }
   return j;
}

Screenshot attached enter image description here


Solution

  • You've mistaken memory complexity for time complexity. The time complexity of the algorithm is O(n). However, the memory, sometimes called space, complexity of the algorithm is O(1), as 4 variables are allocated.