Exercise: Two lists in O(n)

The starter below is correct, but slow. For every item in first it runs x in second, which scans the whole list. That's O(n) work n times: O(n²). With 100,000 items in each list, it's 10 billion checks.

This is one of the most common fixes in real code reviews and in the Performance challenges.

Exercise: rewrite common_items(first, second) so it runs in O(n). It returns the items of first that also appear in second.

  • Keep the order of first.
  • Keep duplicates from first: [1, 1] and [1] give [1, 1].

A plain set(first) & set(second) loses both the order and the duplicates, so it won't pass. Think about which list needs fast in checks.

One test times your function on a small input and an 8 times bigger one. An O(n²) version slows down about 64 times and fails.

Press Check to run the tests.