Home > front end >  Time Complexity of nested for loops with different conditions
Time Complexity of nested for loops with different conditions

Time:09-28

What would be the time complexity for this snippet? I'm having a little trouble understanding how to find the time complexity of nested for loops with different conditions.

I originally thought that it would be n^3 x n^2 which gives O(n^5), but should it be (n^3)^2 which gives O(n^6)?

for(int i = 0; i < n*n; i  ) {
    for(int j = 0; j < n*n*n; j  ) {
        A(); //O(1)
    }
}

CodePudding user response:

If you correctly incremented j in the inner loop (replacing i with j in the inner loop increment step), it would be O(n⁵). The outer loop runs the inner loop times, with each inner loop running times; the total is strictly multiplicative, n² * n³ == n⁵.

As written, it'll never stop running if n > 1 (because j never increments, so if the inner loop begins running, it runs forever).

  • Related