This code has the same time complexity as the code in the question.
for(int i = 0; i < n; i++){ // outer loop
for(int j = 0; j < i; j++){ // inner loop
count++;
}
}
In the first iteration of the outer loop (i = 0), the inner loop doesn’t execute.
In the second iteration of the outer loop (i = 1), the inner loop executes once
.
In the third iteration of the outer loop (i = 2), the inner loop executes twice
.
So, in the last iteration of the outer loop (i = n), the inner loop executes n times
.
Therefore, the total number of times this code executes is
1 + 2 + 3 + … + n
= n(n + 1) / 2
(Sum of Natural Numbers Formula)
= ((n^2) + n) / 2
= O(n^2)
——————
Also, do take a look at these
- https://stackoverflow.com/a/71805214/17112163
- https://stackoverflow.com/a/71537431/17112163
- https://stackoverflow.com/a/71146522/17112163
- https://stackoverflow.com/a/72046825/17112163
- https://stackoverflow.com/a/72046933/17112163