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

0500020004000ncount
Measured
Table
ncount
816
1632
3264
64128
128256
256512
5121,024
10242,048
20484,096
40968,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
  1. Sequential blocks add: n + n = 2n.
  2. Constant factors are dropped: 2n = Θ(n).
  3. 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.