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

Big-O Notation of a for-loop with an conditional inner loop

I am trying to understand the time complexity of this program, and why. I’ve made some notes of what I think it is, but I’m unsure if I understood it correct.

 public static int countSteps(int n) {
    int pow = 2;                             // O(1)
    int steps = 0;                           // O(1)
    for (int i = 0; i < n; i++) {            // O(n)
        if (i == pow) {                      // O(1)
            pow *= 2;                        // O(1)
            for (int j = 0; j < n; j++) {    // O(n)
                steps++;                     // O(1)
            }
        }
        else {
            steps++;                         // O(1)
        }
    }
    return steps; // O(1)
}

The inner loop spends a lot of time iterating through n every time the if-statement is triggered, does that affect the time complexity or is it still constant?

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 :

The outer loop means it’s at least O(n). The inner loop will run only when i is a power of two, so it’s O(n*log n).

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