Exercise 26 of 30 · intermediate · loops · quadratic · break

Nested loop with a break

The code

for i in range(n):
    for j in range(n):
        if j == i:
            break
        work(i, j)

Does the break make it linear?

Count: work 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. For each i, the inner loop stops at j = i: it runs i times.
  2. 0 + 1 + … + (n − 1) = n(n − 1)/2: still quadratic.
  3. A break helps only if it fires after a bounded number of steps.

Common mistake: Assuming any break reduces the class. Count where it fires.

Check: measured count ÷ (n²) settles near 0.499 for large n.