0

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) } } 
3
  • 1
    Why would it be O(n^6)? In the inner loop you have n*n*n*O(1). With the outer loop, you have n*n times the complexity of the loop body, i.e. the complexity of the inner loop: (n*n)*(n*n*n*O(1)). So your initial thought was correct. Commented Sep 27, 2022 at 21:23
  • 1
    Because of the i++ in the inner loop, the complexity is O(n^2), presuming something else will terminate the inner loop. Else, if nothing terminates the inner loop it is O(∞). Commented Sep 27, 2022 at 21:23
  • Haha, that's right. But I suppose that's a typo... Commented Sep 27, 2022 at 21:24

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.