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.
Example 1
arr1 = [1, 2, 2, 1], arr2 = [2, 2][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
arr1 = [4, 9, 5], arr2 = [9, 4, 9, 8, 4][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.
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:
arr1 into a set. This gives us a quick way to ask "is this number in arr1?"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.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 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.