Search code examples
javaalgorithmdata-structurestime-complexityspace-complexity

Time and Space Complexity of Nested loop


Please consider the following algorithm -

for( j = 1; j < n ; j = j * 3)
{
    for( k = 1 ; k <= n ; k = k + 2 )
    {
      r = i + j + k ;

    System.out.println(r);
    }
}

How is the time and space complexity found for this?


Solution

  • The outer loop will have log3 n iterations, the inner loop will have n / 2 iterations (2 is a constant and can be ignored), thus time complexity is O(N log N).

    The space complexity is O(1) because no arrays/lists is created here with regard to N.