Exercise 1 of 30 · beginner · loops · linear

One loop over the input

The code

total = 0
for x in items:        # n items
    total += x

How does the running time grow with n = len(items)?

Count: additions (total += x).

Measured counts

02000400020004000ncount
Measured
Table
ncount
88
1616
3232
6464
128128
256256
512512
10241,024
20482,048
40964,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
  1. The loop body runs once per element: n times.
  2. The body does a constant amount of work.
  3. 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.