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
Understanding the Visualization
1
Input Arrays
nums1 = [1,2,2,1], nums2 = [2,1,2]
2
Find Intersection
Match elements considering their frequencies
3
Result
Output: [2,1,2] (preserving frequencies)
Key Takeaway
🎯 Key Insight: Use frequency counting to handle duplicates - take minimum occurrence count from both arrays
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code