Exercise 2 of 30 · beginner · loops · linear · constants
Two loops one after the other
The code
for x in items:
print(x)
for x in items:
print(x * 2)Is this O(n²) because there are two loops?
Count: print calls.
Measured counts
Table
| n | count |
|---|---|
| 8 | 16 |
| 16 | 32 |
| 32 | 64 |
| 64 | 128 |
| 128 | 256 |
| 256 | 512 |
| 512 | 1,024 |
| 1024 | 2,048 |
| 2048 | 4,096 |
| 4096 | 8,192 |
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
- 2n
- Sequential blocks add: n + n = 2n.
- Constant factors are dropped: 2n = Θ(n).
- Loops multiply only when one is inside the other.
Common mistake: Multiplying the loops. Two loops in sequence add their costs.
Check: measured count ÷ (n) settles near 2.00 for large n.