Problem

Given two integer arrays, return their intersection. Each element in the result must be unique.

Example

Input:  nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Solution

Convert both arrays to sets and find intersection.

def intersection(nums1, nums2):
    return list(set(nums1) & set(nums2))
function intersection(nums1, nums2) {
    const set1 = new Set(nums1);
    return [...new Set(nums2.filter(x => set1.has(x)))];
}
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    unordered_set<int> set1(nums1.begin(), nums1.end());
    unordered_set<int> result;
    for (int x : nums2) {
        if (set1.count(x)) result.insert(x);
    }
    return vector<int>(result.begin(), result.end());
}
public int[] intersection(int[] nums1, int[] nums2) {
    Set<Integer> set1 = new HashSet<>();
    for (int x : nums1) set1.add(x);
    Set<Integer> result = new HashSet<>();
    for (int x : nums2) if (set1.contains(x)) result.add(x);
    return result.stream().mapToInt(Integer::intValue).toArray();
}

Complexity

  • Time: O(n + m)
  • Space: O(n + m)

Explanation

Sets give O(1) lookups. Convert one array to a set, scan the other for matches, dedupe via another set.

Share this article

Comments

Join the discussion. Got a question, found an issue, or want to share your experience?

Leave a Comment

Your email stays private. We just use it for replies.

Nothing to preview yet.

Use **bold**, *italic*, `code`, ```code blocks```, [link](url), > quote, - list