Intersection of Two Arrays II

Multiset intersection — match each element with multiplicity using a counter.

Easy
Time O(N + M) Space O(min(N, M))
LeetCode
3 min read
hash-map arrays

Problem#

Given two integer arrays, return their intersection as a multiset — each element appears as many times as it does in both. Result order doesn’t matter.

Examples#

  • nums1 = [1,2,2,1], nums2 = [2,2][2,2].
  • nums1 = [4,9,5], nums2 = [9,4,9,8,4][4,9] (or [9,4]).

Constraints#

  • 1 <= nums.length <= 1000, 0 <= nums[i] <= 1000.

Hints#

Hint
Count one array; walk the other and decrement on each match.

Approach#

Build counter for the smaller array. Walk the larger; if the counter has a positive count, emit and decrement.

Solution#

Intersection of Two Arrays II
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
if (nums1.size() > nums2.size()) return intersect(nums2, nums1);
unordered_map<int,int> cnt;
for (int v : nums1) ++cnt[v];
vector<int> ans;
for (int v : nums2) {
auto it = cnt.find(v);
if (it != cnt.end() && it->second > 0) { ans.push_back(v); --it->second; }
}
return ans;
}
};

Editorial#

Choosing the smaller array for the counter caps memory at O(min(N, M)). The decrement-on-match step enforces multiset semantics — without it the result would be set intersection.

Complexity#

  • Time: O(N + M).
  • Space: O(min(N, M)).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.