How do you find the intersection of two arrays, and what do the different interpretations of that word mean?
The word intersection hides a choice that interviewers will make you state. Does it mean the distinct common values, the common values with duplicates preserved, or the common values with their multiplicities matched? Each gives a different answer for the same inputs, so say which one you are implementing before you write a line of code.
def intersection(a, b):
seen = set(a)
return [value for value in b if value in seen]
print(intersection([1, 2, 3, 4], [3, 4, 5]))
print(intersection([1, 2], [3, 4]))The outputs are 3, 4 and an empty list. The first call finds the two values that appear in both arrays. The second finds none, so the list is empty.
The mechanism is that a set turns the membership question into a constant-time lookup. You put the first array into a set, then walk the second array and keep the values that are found. Without the set you would be scanning the first array for every element of the second, which is quadratic. The complexity is linear in the combined length, with space proportional to the number of distinct values in the first array.
The trade-off to name is space against time, plus an ordering subtlety. This version returns the common values in the order they appear in the second array, and it does not deduplicate them, so if both arrays contain three copies of the same value you get three copies back. If you want distinct values, add the result to a set. If you want multiplicities matched, you need a count table rather than a set, and you should say so. The honest interview answer names the interpretation first and then gives the matching implementation.