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 += 1

What is the expected time with a hash set?

Count: set operations. Two inputs: use n and m.

Measured counts

0500020004000ncount
Measured (with m = n)
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 + m) expected
Extra space
Θ(n)
Exact count
n + m
  1. Building the set: n expected-O(1) inserts.
  2. Probing: m expected-O(1) lookups.
  3. 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.