Intersection of two lists
Write common(a, b) that returns the values found in both lists, without duplicates, in sorted order.
common([4, 9, 5, 4], [9, 4, 9, 8, 4]) # [4, 9]
common([1, 2], [3]) # []
Show hint
Python sets support & for intersection.
Show solution
def common(a, b):
return sorted(set(a) & set(b))
Building the two sets is O(len(a) + len(b)), and the intersection checks each item of the smaller set against the larger. Sorting the result adds O(k log k) for k shared values. A nested loop with in on lists would be O(len(a) × len(b)).
Want a problem like this every day? See today's problem and keep a streak going.