-1

Sorry if this question is a duplicate ,or is kind of stupid ,but I'm really new to algorithm development) Can you explain me what is the complexity of following piece of code

for (int i=0; i<n; i++) {
    for (int j=0; j<i; j++) {
        do stuff...
    }
}

is the complexity of this code n^2 or nlogn? Thanks

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Andre Liberty
  • 707
  • 1
  • 9
  • 17
  • 3
    Possible duplicate of [What is the Big-O of a nested loop, where number of iterations in the inner loop is determined by the current iteration of the outer loop?](http://stackoverflow.com/questions/362059/what-is-the-big-o-of-a-nested-loop-where-number-of-iterations-in-the-inner-loop) – Liam Nov 14 '16 at 14:24
  • 2
    Please stop malforming your own code. I've had to roll this back 3 times now – Liam Nov 14 '16 at 14:26

1 Answers1

1

The complexity is O(n^2).

For first iteration of outer loop, inner loop will iterate 0 times

For second iteration of outer loop, inner loop will iterate 1 times.

For third iteration of outer loop, inner loop will iterate 2 times.

.........

For nth iteration of outer loop, inner loop will iterate n - 1 times.

Total number of iterations = 0 + 1 + 2 + 3 + 4 ...... + (n - 1)

We know, the sum of arithmetic series

1 + 2 + 3 + ..... + (n - 2) + (n - 1) + n = (n * (n + 1)) / 2 

So,

 0 + 1 + 2 + 3 + 4 ...... + (n - 1) 
 = (n * (n - 1)) / 2 
 ~ n^2

Considering the do stuff phase will execute in constant time, the overall time complexity is O(n^2).

Kaidul
  • 15,409
  • 15
  • 81
  • 150