Solution: Big O of a Nested Loop with Addition
This review provides a detailed analysis of the time complexity of the Nested Loop with Addition problem!
We'll cover the following...
Given Code #
Press + to interact
class NestedLoop {public static void main(String[] args) {int n = 10; // 1 step --> Note: n can be anything. This is just an exampleint sum = 0; // 1 stepdouble pie = 3.14; // 1 stepfor (int var = 0; var < n; var = var + 3) { // n/3 stepsSystem.out.println("Pie: " + pie); // n/3 stepsfor (int j = 0; j < n; j = j + 2) { // (n/3 * n/2) stepssum++; // (n/3 * n/2) stepsSystem.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 1 unit of time. The comparison (var < n
) gets executed times and the increment runs times.
Similarly, (int j = 0)
runs times , the comparison (j < n
) runs (the test case runs once more than the whole loop where boundary check fails!) and the increment (j = j + 2)
gets executed times for each iteration of the outer loop–which makes it run a total of ...