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.
- 1 ≤ nums1.length, nums2.length ≤ 1000
- 0 ≤ nums1[i], nums2[i] ≤ 1000
Example
nums1 = [1,2,2,1], nums2 = [2,2][2,2]A brute-force approach would check each element of nums1 against nums2, removing matched elements to avoid duplicates, resulting in O(n*m) time complexity. The optimal approach uses a frequency map to count occurrences in nums1, then iterates through nums2 to collect common elements up to the minimum count. For example, nums1 has two '2's, nums2 has two '2's, so the intersection includes two '2's.
Approach
Straightforward Solution
A naive nested loop approach compares each element in nums1 with every element in nums2, removing matched elements to avoid duplicates. This approach is O(n*m) and inefficient for large inputs.
Core Observation
The intersection requires counting how many times each element appears in both arrays and including it in the result the minimum number of times it appears in either array.
Path to Optimal
Recognizing that counting frequencies is key, the problem transforms into a frequency comparison. Using a hash map (or Counter) to store counts of nums1 elements allows O(1) average lookup. Iterating through nums2 and checking counts in the map enables collecting the intersection efficiently in O(n + m) time.
Optimal Approach
Build a frequency map of nums1 using a hash map. Iterate through nums2, and for each element, if it exists in the map with a positive count, append it to the result and decrement the count. This ensures each element is included only as many times as it appears in both arrays, achieving O(n + m) time and O(n) space.
Time
O(n + m)
Building the frequency map takes O(n) time, iterating through nums2 takes O(m), and each hash map operation is O(1) on average, resulting in linear time relative to input sizes.
Space
O(n)
The frequency map stores counts for elements in nums1, which in the worst case can be all n elements. The output array space is not counted as auxiliary space.
Pattern Spotlight
Hash Maps (Frequency Counting)
When needing to find common elements with counts between two arrays, use a hash map to store frequencies of one array and then iterate the other to efficiently find intersections by decrementing counts.
Solution
| 1 | from collections import Counter |
| 2 | |
| 3 | class Solution: |
| 4 | def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: |
| 5 | remaining_counts = Counter(nums1) |
| 6 | intersection = [] |
| 7 | |
| 8 | for num in nums2: |
| 9 | if remaining_counts[num] > 0: |
| 10 | intersection.append(num) |
| 11 | remaining_counts[num] -= 1 |
| 12 | |
| 13 | return intersection |
Step-by-Step Solution
Build Frequency Map for First Array Elements
| 5 | remaining_counts = Counter(nums1) |
| 6 | intersection = [] |
Objective
To count the occurrences of each element in nums1 using a hash map for efficient lookup.
Key Insight
Counting frequencies upfront transforms the problem from repeated searches to constant-time lookups. This precomputation enables efficient intersection detection by tracking how many times each element can still be matched.
Interview Quick-Check
Core Logic
Using a hash map to store frequencies allows O(1) average-time checks for whether an element from nums2 can be included in the intersection.
Common Pitfalls & Bugs
Failing to use a frequency map leads to inefficient nested loops and duplicate counting.
Iterate Through Second Array to Collect Intersection Elements
| 8 | for num in nums2: |
| 9 | if remaining_counts[num] > 0: |
| 10 | intersection.append(num) |
| 11 | remaining_counts[num] -= 1 |
Objective
To traverse nums2 and append elements to the intersection list only if they appear in nums1 with remaining count.
Key Insight
By checking the frequency map for positive counts, the algorithm ensures each element is added only as many times as it appears in both arrays. Decrementing the count after adding prevents duplicates beyond the allowed frequency.
Interview Quick-Check
Core Logic
The check for positive count in the frequency map and subsequent decrement enforces correct duplicate handling in the intersection.
State & Boundaries
Iterating through nums2 ensures all potential intersection elements are considered, respecting their counts.
Common Pitfalls & Bugs
Not decrementing the count after adding an element can cause duplicates to be included more times than allowed.
Return the Computed Intersection List
| 13 | return intersection |
Objective
To output the final list containing the intersection elements with correct counts.
Key Insight
Returning the accumulated list completes the solution, providing the intersection in any order as required by the problem.
Interview Quick-Check
Core Logic
Returning the intersection list after processing both arrays ensures the result reflects all common elements with correct multiplicities.
Line Analysis
This solution has 2 Critical lines interviewers watch for.
if remaining_counts[num] > 0:
Check if the current element from nums2 has a positive count in the frequency map.
This condition ensures that only elements present in nums1 and not yet fully matched are added to the intersection, preventing overcounting.
remaining_counts = Counter(nums1)
Create a frequency map counting occurrences of each element in nums1.
This line sets up the essential data structure that enables constant-time frequency lookups, transforming the problem from repeated searches to efficient counting.
remaining_counts[num] -= 1
Decrement the count of the current element in the frequency map.
Reducing the count prevents the same element from being added more times than it appears in nums1, enforcing correct duplicate handling.
intersection.append(num)
Append the current element to the intersection list.
Adding the element here records a valid intersection occurrence, respecting the frequency constraints from nums1.
intersection = []
Initialize the result list that will hold the intersection elements.
This list stores the shared elements found between the two arrays, including duplicates when both arrays contain enough copies. It starts empty because no matches have been processed yet.
for num in nums2:
Begin iterating through each element in nums2.
This loop examines every element in nums2 to determine if it should be included in the intersection based on the frequency map.
return intersection
Return the list containing the intersection elements.
This line outputs the final result, completing the function by providing the intersection with correct multiplicities.
Test Your Understanding
Why do we decrement the count in the frequency map after adding an element to the intersection?
Decrementing the count ensures that each element is included in the intersection only as many times as it appears in both arrays, preventing overcounting duplicates.
Related Problems
Hash Maps pattern
Don't just read it. Drill it.
Reconstruct Intersection of Two Arrays II from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Intersection of Two Arrays II drill