Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Time Complexity of nested for loops with different conditions

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading