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