Find Common Elements Between Two Arrays

easy array hash set

Problem

You are given two integer arrays nums1 and nums2. Return an array answer of length 2 where answer[0] is the count of indices i such that nums1[i] also exists in nums2, and answer[1] is the count of indices i such that nums2[i] also exists in nums1.

Inputnums1 = [2,3,2], nums2 = [1,2]
Output[2,1]
In nums1, both 2's appear in nums2 (count 2). In nums2, only 2 appears in nums1 (count 1).

def find_intersection_values(nums1, nums2):
    set1 = set(nums1)
    set2 = set(nums2)
    a = sum(1 for x in nums1 if x in set2)
    b = sum(1 for x in nums2 if x in set1)
    return [a, b]
function findIntersectionValues(nums1, nums2) {
  const set1 = new Set(nums1);
  const set2 = new Set(nums2);
  let a = 0, b = 0;
  for (const x of nums1) if (set2.has(x)) a++;
  for (const x of nums2) if (set1.has(x)) b++;
  return [a, b];
}
class Solution {
    public int[] findIntersectionValues(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for (int x : nums1) set1.add(x);
        for (int x : nums2) set2.add(x);
        int a = 0, b = 0;
        for (int x : nums1) if (set2.contains(x)) a++;
        for (int x : nums2) if (set1.contains(x)) b++;
        return new int[]{a, b};
    }
}
vector<int> findIntersectionValues(vector<int>& nums1, vector<int>& nums2) {
    unordered_set<int> set1(nums1.begin(), nums1.end());
    unordered_set<int> set2(nums2.begin(), nums2.end());
    int a = 0, b = 0;
    for (int x : nums1) if (set2.count(x)) a++;
    for (int x : nums2) if (set1.count(x)) b++;
    return {a, b};
}
Time: O(n + m) Space: O(n + m)