progress

~/problems / Arrays & hashing / Complexity analysis

Fast membership with a set

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Write common_values(a: list[int], b: list[int]) -> list[int] that returns every value appearing in both lists, each value once, in increasing order.

common_values([5, 1, 3, 3, 9], [3, 7, 5, 5])   # [3, 5]
common_values([1, 2], [3, 4])                  # []
  • 0 <= len(a), len(b) <= 2 * 10^5; values are in [-10^9, 10^9] and may repeat.
  • [x for x in a if x in b] hides a second loop: x in b scans all of b, so it's O(len(a) * len(b)).
  • ⭐ Bonus: a speed test with 200,000 values per list earns a star in O(n log n). Slower correct code still passes.
Show hint

x in some_set is O(1) on average, x in some_list is O(n). Turn the lists into sets first.

Topic: Complexity analysis. Big-O from constraints: n = 10^5 means O(n log n); know the Python constant factors.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc