Exercise 1 of 30 · beginner · loops · linear
One loop over the input
The code
total = 0
for x in items: # n items
total += xHow does the running time grow with n = len(items)?
Count: additions (total += x).
Measured counts
Table
| n | count |
|---|---|
| 8 | 8 |
| 16 | 16 |
| 32 | 32 |
| 64 | 64 |
| 128 | 128 |
| 256 | 256 |
| 512 | 512 |
| 1024 | 1,024 |
| 2048 | 2,048 |
| 4096 | 4,096 |
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
- The loop body runs once per element: n times.
- The body does a constant amount of work.
- n × O(1) = Θ(n). Only total and the loop variable are stored: O(1) extra space.
Common mistake: Counting the work inside the body as "n" too. A constant-time body contributes a constant factor, not another n.
Check: measured count ÷ (n) settles near 1.00 for large n.