Exercise 13 of 30 · beginner · multiple inputs · linear
Sequential loops over two inputs
The code
for a in first: # n items
seen.add(a)
for b in second: # m items
if b in seen: hits += 1What is the expected time with a hash set?
Count: set operations. Two inputs: use n and m.
Measured counts
Table
| n | count |
|---|---|
| 8 | 16 |
| 16 | 32 |
| 32 | 64 |
| 64 | 128 |
| 128 | 256 |
| 256 | 512 |
| 512 | 1,024 |
| 1024 | 2,048 |
| 2048 | 4,096 |
| 4096 | 8,192 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n + m) expected
- Extra space
- Θ(n)
- Exact count
- n + m
- Building the set: n expected-O(1) inserts.
- Probing: m expected-O(1) lookups.
- Sequential blocks add: Θ(n + m). The set stores up to n elements.
Common mistake: Dropping m because it is "another input". Both sizes matter; neither dominates in general.
Check: measured count ÷ (n) settles near 2.00 for large n.