Intersection of Two Arrays II - Problem
Find the common elements between two integer arrays, keeping track of how many times each element appears in both arrays. Unlike a simple set intersection, this problem requires you to preserve duplicates based on their frequency in both arrays.
Given two integer arrays nums1 and nums2, return an array containing their intersection where:
- Each element appears as many times as it shows up in both arrays
- If an element appears 3 times in
nums1and 2 times innums2, it should appear 2 times in the result - The result can be returned in any order
Example: nums1 = [1,2,2,1], nums2 = [2,2] โ Result: [2,2]
Input & Output
example_1.py โ Python
$
Input:
nums1 = [1,2,2,1], nums2 = [2,2]
โบ
Output:
[2,2]
๐ก Note:
Element 2 appears twice in both arrays, so it appears twice in the intersection. Element 1 appears in nums1 but not in nums2, so it's excluded from the result.
example_2.py โ Python
$
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. Element 5 only appears in nums1, element 8 only appears in nums2.
example_3.py โ Python
$
Input:
nums1 = [1,2], nums2 = [1,1]
โบ
Output:
[1]
๐ก Note:
Element 1 appears once in nums1 and twice in nums2. The intersection frequency is min(1,2) = 1, so 1 appears once in the result.
Constraints
- 1 โค nums1.length, nums2.length โค 1000
- 0 โค nums1[i], nums2[i] โค 1000
- Follow-up questions:
- What if nums2 cannot fit in memory? Use external sorting
- What if nums1 is much smaller than nums2? Build hash table from smaller array
Visualization
Tap to expand
Understanding the Visualization
1
Count friend's cards
First, count how many of each card your friend has
2
Check your cards
Go through your cards and see which ones your friend also has
3
Make the trade
For each match, trade one copy and reduce both counts
Key Takeaway
๐ฏ Key Insight: Intersection frequency = min(your_count, friend_count) for each card type
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code