Intersection of Two Arrays II - Problem

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

The intersection should preserve the frequency of elements - if an element appears 3 times in both arrays, it should appear 3 times in the result.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,2,2,1], nums2 = [2,1,2]
Output: [2,1,2]
💡 Note: Element 2 appears twice in both arrays, so it appears twice in result. Element 1 appears twice in nums1 but only once in nums2, so it appears once in result.
Example 2 — Different Frequencies
$ Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
💡 Note: Element 4 appears once in nums1 and twice in nums2, so it appears once in result. Element 9 appears once in nums1 and twice in nums2, so it appears once in result.
Example 3 — No Common Elements
$ Input: nums1 = [1,2,3], nums2 = [4,5,6]
Output: []
💡 Note: No elements are common between the two arrays, so the intersection is empty.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 1000
  • 0 ≤ nums1[i], nums2[i] ≤ 1000

Visualization

Tap to expand
Intersection of Two Arrays II INPUT nums1 = [1,2,2,1] 1 2 2 1 nums2 = [2,1,2] 2 1 2 Frequency in nums1: 1 --> 2 times 2 --> 2 times Find common elements with min frequency ALGORITHM STEPS 1 Build Hash Map Count freq of nums1 map = { 1: 2, 2: 2 } 2 Iterate nums2 Check if elem in map 3 If count > 0 Add to result, decr count 4 Return Result Array with intersection 2 in map? Yes --> result=[2] 1 in map? Yes --> result=[2,1] 2 in map? Yes --> result=[2,1,2] FINAL RESULT Output: [2, 1, 2] 2 1 2 Verification: 2 appears 2x in both - OK 1 appears 2x in nums1 1 appears 1x in nums2 - OK Complexity Time: O(n + m) Space: O(min(n,m)) OK Key Insight: Use a HashMap to count frequencies of elements in the first array. Then iterate through the second array, checking if each element exists in the map with count > 0. This preserves element frequency in the result. TutorialsPoint - Intersection of Two Arrays II | Hash Map Approach
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
125.0K Views
High Frequency
~15 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen