Exercise 3 of 30 · beginner · loops · quadratic · nested

A loop inside a loop

The code

pairs = 0
for i in range(n):
    for j in range(n):
        pairs += 1

How many times does the inner statement run?

Count: increments of pairs.

Measured counts

01.0e+2k2.0e+2k200400ncount
Measured
Table
ncount
864
16256
321,024
644,096
12816,384
25665,536
512262,144

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. For each of the n values of i, the inner loop runs n times.
  2. Nested loops multiply: n × n = n².

Common mistake: Adding the loops (2n). The inner loop restarts for every i.

Check: measured count ÷ (n²) settles near 1.00 for large n.