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