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 += 1Write the cost in terms of the input sizes.
Count: comparisons. Two inputs: use n and m.
Measured counts
Table
| n | count |
|---|---|
| 8 | 64 |
| 16 | 256 |
| 32 | 1,024 |
| 64 | 4,096 |
| 128 | 16,384 |
| 256 | 65,536 |
| 512 | 262,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
- The inner loop runs m times for each of the n outer iterations.
- Total n · m. Do not collapse it to n²: if m is tiny (say 3), the loop is effectively linear.
- 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.