← All Lessons Lesson 40 / 68
Lesson 40

Finding the Unique Intersection of Two Arrays

The Problem: What Do Two Lists Have in Common?

Imagine you have two shopping lists. The first list has the items you bought today, and the second list has the items your friend bought. You want to know: which items appear on both lists? That shared set of items is called the intersection.

In this problem, instead of shopping items we have two arrays (an array is just an ordered list of values) of whole numbers, called arr1 and arr2. Our job is to write a function that returns a new array containing the numbers that show up in both arrays.

There is one important extra rule: each number in the answer must appear only once. Even if a number is repeated many times in the inputs, it should show up at most once in the result. We can return the answer in any order — the grader does not care about the arrangement.

Reading the Examples

Example 1

  • Input: arr1 = [1, 2, 2, 1], arr2 = [2, 2]
  • Output: [2]

Let's walk through it. Which numbers live in both arrays? The number 2 is in arr1, and 2 is also in arr2. The number 1 is in arr1, but 1 is not in arr2, so it does not count. So the only shared number is 2. Notice that even though 2 appears twice in both arrays, the answer lists it just once, because the result must be unique.

Example 2

  • Input: arr1 = [4, 9, 5], arr2 = [9, 4, 9, 8, 4]
  • Output: [4, 9]

Here, 4 is in both arrays, and 9 is in both arrays. The number 5 is only in arr1, and 8 is only in arr2, so neither one makes the cut. The shared numbers are 4 and 9, each listed once.

How to Think About Solving It

A simple and fast plan uses a set. A set is like a bag that automatically refuses duplicates — if you try to add the same value twice, it just keeps one copy. This matches our "must be unique" rule perfectly.

A clear step-by-step idea:

  1. Put every number from arr1 into a set. This gives us a quick way to ask "is this number in arr1?"
  2. Go through each number in arr2. If that number is found in the set from step 1, it belongs in both arrays, so add it to a second "result" set.
  3. Using a set for the result makes sure each shared number is stored only once.
  4. Copy the result set into an array and return it.

This approach is efficient because checking whether a number is in a set is very fast, so we only need one pass through each array.

The Starting Code

The editor gives you a function to fill in:

class Solution {
public:
    vector<int> uniqueIntersections( vector<int> &arr1, vector<int> &arr2 ) {

    }
};

The function receives the two arrays as arr1 and arr2 and must return a vector<int> (C++'s name for a growable array of integers) holding the unique shared values.

Finding the Unique Intersection of Two Arrays
Diagram — click to zoom (scroll / drag to pan)