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 nums1 and 2 times in nums2, 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
Card Trading IntersectionYour Cards:PikachuCharizardCharizardPikachuFriend's Cards:CharizardCharizardFriend's Count:Charizard: 2Checking your cards...Tradeable Cards (Result):CharizardCharizardYou both have 2 Charizards!
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
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
142.8K 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