Intersection of Two Arrays II

easy array hash map counter

Problem

Return the intersection of two arrays preserving the multiplicity — each value appears as many times as it shows up in both arrays.

Inputnums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]
Output[4, 9]
Count nums1's values, then for each value in nums2 emit and decrement if positive.

from collections import Counter

def intersect(nums1, nums2):
    cnt = Counter(nums1)
    out = []
    for x in nums2:
        if cnt[x] > 0:
            out.append(x)
            cnt[x] -= 1
    return out
function intersect(nums1, nums2) {
  const cnt = new Map();
  for (const x of nums1) cnt.set(x, (cnt.get(x) || 0) + 1);
  const out = [];
  for (const x of nums2) {
    if ((cnt.get(x) || 0) > 0) {
      out.push(x);
      cnt.set(x, cnt.get(x) - 1);
    }
  }
  return out;
}
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> cnt = new HashMap<>();
        for (int x : nums1) cnt.merge(x, 1, Integer::sum);
        List<Integer> out = new ArrayList<>();
        for (int x : nums2) {
            if (cnt.getOrDefault(x, 0) > 0) { out.add(x); cnt.merge(x, -1, Integer::sum); }
        }
        return out.stream().mapToInt(Integer::intValue).toArray();
    }
}
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
    unordered_map<int, int> cnt;
    for (int x : nums1) cnt[x]++;
    vector<int> out;
    for (int x : nums2) if (cnt[x] > 0) { out.push_back(x); cnt[x]--; }
    return out;
}
Time: O(n + m) Space: O(min(n, m))