Complexity and efficiency · 11 / 15 Exercise Medium

Efficient intersection

Objective

Create a Python program that finds the elements common to two lists and compares the cost of doing it with nested loops (O(n · m)) and with sets (O(n + m)).

Instructions

  • Read two lines with integers separated by spaces (the first list has n elements and the second m).
  • Compute the common ones with set(a) & set(b) (no duplicates, sorted from lowest to highest) and show them with Common: x y z, or No common elements if there are none.
  • Show Comparisons with nested loops: P (the product n × m) and Set operations: S (the sum n + m).
Input
1 2 3 4 5
4 5 6 7
Output
Common: 4 5
Comparisons with nested loops: 20
Set operations: 9

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise