Loop runtime question

algorithm-analysisbig oloopsruntime

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 values j takes on. We remove the diagonal (which has n entries) and the upper right half because j will never be larger or equal to i. We are then left with an area of (n² - n)/2.

 i  | values of j     | no of j values
----+-----------------+---------------
 0  | · · · · ·  ⋯  · |  0
 1  | 0 · · · ·  ⋯  · |  1
 2  | 0 1 · · ·  ⋯  · |  2
 3  | 0 1 2 · ·  ⋯  · |  3
 4  | 0 1 2 3 ·  ⋯  · |  4
 :  | : : : :    :  : |  :
n-1 | 0 1 2 3 ⋯ n-2 · | n-1
                       =====
                  SUM: (n² - n)/2

Mathematical explanation

The outer loop executes n times, the inner loop i times. We can write the number of executions of the inner loop body as mi=1 i with m = n-1. The sum of all natural numbers up to including m can also be written as m·(m + 1)/2 (the formula for triangular numbers), which leads to n(n-1)/2.

Conclusion

Using either method, we can determine that the nested loops have a complexity of O((n² - n)/2) = O(n²).