Search⌘ K

Solution: Big (O) of a Nested Loop with Addition

Explore how to break down and calculate the running time of nested loops using Big O notation. This lesson explains each loop component, counts executions, and guides you through deriving the overall time complexity, helping you develop a strong foundation in asymptotic analysis for coding interviews.

Given code

Java
class NestedLoop {
public static void main(String[] args) {
int n = 10; // 1 step --> Note: n can be anything. This is just an example
int sum = 0; // 1 step
double pie = 3.14; // 1 step
for (int var = 0; var < n; var = var + 3) { // n/3 steps
System.out.println("Pie: " + pie); // n/3 steps
for (int j = 0; j < n; j = j + 2) { // (n/3 * n/2) steps
sum++; // (n/3 * n/2) steps
System.out.println("Sum = " + sum); // (n/3 * n/2) steps
}
}
}
}

Solution breakdown

The first for loop on line 7 can be broken down into 3 parts:

  • initialization
  • comparison
  • incrementation

Since the initialization (int var = 0) only happens once in the entire program, it takes one unit of time. The comparison (var < n) gets executed (n3+1)(\frac{n}{3} + 1) times and the increment runs n3\frac{n}{3} times.

Similarly, (int j = 0) runs n3\frac{n}{3} times , the comparison (j < n) runs n3×{n2 +1}\frac{n}{3} \times \{\frac{n}{2}\ + 1\} (the test case runs once more than the whole loop where boundary check fails!), and the increment (j = j + 2) gets executed n2\frac{n}{2} times for each iteration of the outer loop–which makes it run a total of n3×n2=n26\frac{n}{3} \times \frac{n}{2} = \frac{n^2}{6} ...