Intersection of Two Arrays

easy array hash set

Problem

Return the unique values that appear in both nums1 and nums2. Each value in the result must be unique; order does not matter.

Inputnums1 = [1, 2, 2, 1], nums2 = [2, 2]
Output[2]
Hash nums1 into a set, then collect values from nums2 that hit.

def intersection(nums1, nums2):
    a = set(nums1)
    out = set()
    for x in nums2:
        if x in a:
            out.add(x)
    return list(out)
function intersection(nums1, nums2) {
  const a = new Set(nums1);
  const out = new Set();
  for (const x of nums2) {
    if (a.has(x)) out.add(x);
  }
  return [...out];
}
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> a = new HashSet<>();
        for (int x : nums1) a.add(x);
        Set<Integer> out = new HashSet<>();
        for (int x : nums2) if (a.contains(x)) out.add(x);
        return out.stream().mapToInt(Integer::intValue).toArray();
    }
}
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    unordered_set<int> a(nums1.begin(), nums1.end());
    unordered_set<int> out;
    for (int x : nums2) if (a.count(x)) out.insert(x);
    return {out.begin(), out.end()};
}
Time: O(n + m) Space: O(min(n, m))