Skip to content

2956. Find Common Elements Between Two Arrays

  • Time: $O(n + m)$
  • Space: $O(n + m)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  vector<int> findIntersectionValues(vector<int>& nums1, vector<int>& nums2) {
    const unordered_set<int> set1{nums1.begin(), nums1.end()};
    const unordered_set<int> set2{nums2.begin(), nums2.end()};
    const int ans1 = ranges::count_if(
        nums1, [&set2](int num) { return set2.contains(num); });
    const int ans2 = ranges::count_if(
        nums2, [&set1](int num) { return set1.contains(num); });
    return {ans1, ans2};
  }
};
1
2
3
4
5
6
7
8
9
class Solution {
  public int[] findIntersectionValues(int[] nums1, int[] nums2) {
    Set<Integer> nums1Set = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
    Set<Integer> nums2Set = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
    final int ans1 = (int) Arrays.stream(nums1).filter(nums2Set::contains).count();
    final int ans2 = (int) Arrays.stream(nums2).filter(nums1Set::contains).count();
    return new int[] {ans1, ans2};
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def findIntersectionValues(
      self,
      nums1: list[int],
      nums2: list[int],
  ) -> list[int]:
    nums1Set = set(nums1)
    nums2Set = set(nums2)
    return [sum(num in nums2Set for num in nums1),
            sum(num in nums1Set for num in nums2)]