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
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
- For each i, the inner loop stops at j = i: it runs i times.
- 0 + 1 + … + (n − 1) = n(n − 1)/2: still quadratic.
- 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.