Exercise 12 of 30 · intermediate · multiple inputs · nested

Nested loops over two different inputs

The code

for a in first:        # n items
    for b in second:   # m items
        if a == b: count += 1

Write the cost in terms of the input sizes.

Count: comparisons. Two inputs: use n and m.

Measured counts

01.0e+2k2.0e+2k200400ncount
Measured (with m = n)
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 · m)
Extra space
O(1)
Exact count
n · m
  1. The inner loop runs m times for each of the n outer iterations.
  2. Total n · m. Do not collapse it to n²: if m is tiny (say 3), the loop is effectively linear.
  3. With a hash set of `second`, it drops to Θ(n + m) expected.

Common mistake: Writing O(n²). Use one variable per independent input size.

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