Exercise 4 of 30 · beginner · loops · quadratic · arithmetic series
Inner loop that depends on the outer index
The code
for i in range(n):
for j in range(i): # 0, 1, 2, …, n-1 iterations
compare(i, j)The inner loop is shorter on average. Does that change the class?
Count: compare calls.
Measured counts
Table
| n | count |
|---|---|
| 8 | 28 |
| 16 | 120 |
| 32 | 496 |
| 64 | 2,016 |
| 128 | 8,128 |
| 256 | 32,640 |
| 512 | 130,816 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n²)
- Extra space
- O(1)
- Exact count
- n(n − 1) / 2
- The inner loop runs i times for i = 0 … n − 1.
- Total: 0 + 1 + … + (n − 1) = n(n − 1)/2.
- n(n − 1)/2 = n²/2 − n/2, whose leading term is n²/2: Θ(n²). Halving the work halves the constant, not the class.
Common mistake: Calling it O(n log n) because the inner loop "gets shorter". It shrinks linearly, not geometrically.
Check: measured count ÷ (n²) settles near 0.499 for large n.