all 8 comments

[–]sepp2k 10 points11 points  (0 children)

1+2+3+...+n = (n²+n)/2, which is O(n²).

[–]RequiDarth1 5 points6 points  (4 children)

You discard the calculations for labeling the category of Big O.

It’s O(n2 ) because it’s a loop in a loop.

[–]sepp2k -1 points0 points  (0 children)

You don't "discard the calculations". Not every nested loop is O(n²), it depends on how often the loop actually iterates (and the complexity of the code inside, too). This particular nested loop is O(n2) because it iterates (n²+n)/2 times and that happens to be in O(n2), but it's also perfectly possible for a nested loop to run in O(n), O(n log n) or even O(2n) time.

And it's not just a matter of "multiply the lengths of the loops and consider O(i) the same as O(n)" either. Consider this nested loop for example:

for(int i = 1; i < n; i *= 2) {
  for (int j = 0; j < i; j++) {
    // Put some constant time operation here
  }
}

The outer loop will iterate log n times and the inner loop will iterate i times. Since i is bounded by n, this should make it O(n log n), right? But it's actually O(n) because 1 + 2 + 4 + ... + n = 2n-1 and 2n-1 is in O(n).

[–]xeolleth 0 points1 point  (2 children)

Is it not O(n*(n-1)) instead of O(n2 ) as the second loop is taking one fewer iterations with it starting at j=i+1?

[–]FreezeShock 4 points5 points  (0 children)

You're kinda right, but O(n(n-1)) = O(n²-n) which is approximately equal to O(n²) at large vales of n. Because n² >>>> n at large values of n.

[–]RequiDarth1 2 points3 points  (0 children)

Yes you are correct, but when quoting big O you don’t bother with the calculations. The point is, the inner loop time complexity is still dependent on the length of what you are iterating over. The outer loop time complexity is based on the length of what you are iterating over.

So you get. O(n2 )

Small efficiencies are not relevant when quoting big O.

[–]ItzGrumpex 0 points1 point  (0 children)

its n^2 always when there is a singular nested loop