Arrays and strings · Exercise 9 of 100

Array Intersection

The distinct intersection of two arrays contains each value that appears in both. Make a set of the first array's values, then scan the second array for matches. Cross each match off the set so repeated entries count only once.

Try it yourself

Two birdwatchers record species codes [4, 7, 7, 9, 12] and [7, 7, 11, 12, 4]. How many distinct codes did both record?

One-step hint

Circle each code on the first list that also appears on the second. Before counting, cross out repeats among the circled codes.

Worked solution
  1. The first watcher's distinct codes are 4, 7, 9 and 12. Match the first 7 from the second list and cross it off, so the next 7 adds nothing.
  2. Skip 11, then match 12 and 4. Together with 7, that gives 3 distinct shared codes.
DSA compiler