Math Fundamentals18 sections · 814 units
Open in Course

Why Nested Loops are O(n^2)

Sum explains the complexity

When you have two nested loops both running from 11 to nn, the total operations is n+n+...+nn + n + ... + n (nn times), which equals n2n^2.

But what if the inner loop runs from ii to nn? Then you compute n+(n1)+(n2)+...+1n + (n-1) + (n-2) + ... + 1. Using the formula, this equals n(n+1)2\frac{n(n+1)}{2}, which is O(n2)O(n^2).

The coefficient changes (12\frac{1}{2} instead of 11), but the dominant term is still n2n^2. This is why checking all pairs in an array takes quadratic time.