I had an exam today and I feel that I did pretty well, except I could not for the life of me figure out what appears to be an unbelievably simple question.
We were asked to give theta notation run times for a few programs(with input size n), and this was one of them:
int sum = 0;
for int i = 0; i < n; i++
for int j = 0; j < i; j++
sum++
So I know iterating from 0 to n on both loops would render a O(n2) run time… but with the second loop only iterating to the first loop control variable, I would assume it must be faster… because the second loop never even reaches n iterations until the very last loop-through?
I'm gonna freak out if its O(n2) and I over thought this…
Best Answer
The complexity class is
O(n²)
.Visual explanation
Imagine a
n·n
square which lists all the valuesj
takes on. We remove the diagonal (which hasn
entries) and the upper right half becausej
will never be larger or equal toi
. We are then left with an area of(n² - n)/2
.Mathematical explanation
The outer loop executes
n
times, the inner loopi
times. We can write the number of executions of the inner loop body as∑mi=1 i
withm = n-1
. The sum of all natural numbers up to includingm
can also be written asm·(m + 1)/2
(the formula for triangular numbers), which leads ton(n-1)/2
.Conclusion
Using either method, we can determine that the nested loops have a complexity of
O((n² - n)/2) = O(n²)
.