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

Complexity of three for loops

I was wondering if time complexity of the following code is O(n^3) or O(n^2)

public void firstMethod() {
    for(int i = 0; i < 6; i++) {
        for(int j = 0; j < 6; j++) {
            secondMethod();
       }
   }
}

public void secondMethod(){
        for(int i = 0; i < 6; i++) {
            System.out.println("This is a test to observe complexity");
        }
}

>Solution :

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

This is O(1) because the runtime is constant.

Now, had you written the following:

public void firstMethod(int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            secondMethod(n);
       }
   }
}

public void secondMethod(int n) {
    for (int i = 0; i < n; i++) {
        System.out.println("This is a test to observe complexity");
    }
}

Then firstMethod would be O(n^3) for runtime complexity.

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