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

050k1.0e+2k200400ncount
Measured
Table
ncount
828
16120
32496
642,016
1288,128
25632,640
512130,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
  1. The inner loop runs i times for i = 0 … n − 1.
  2. Total: 0 + 1 + … + (n − 1) = n(n − 1)/2.
  3. 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.