Solution: Big O of a Nested Loop with Addition
Understand how to break down nested loops to measure their time complexity. This lesson guides you through analyzing each loop component and calculating the overall Big O complexity, helping you improve your algorithm evaluation skills.
We'll cover the following...
We'll cover the following...
Given Code #
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 ...