π§© Problem Statement
Given two integer arrays nums1
and nums2
, return an array of their intersection, where each element in the result should appear as many times as it shows in both arrays.
The result can be returned in any order.
π’ Examples
python
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9] # or [9,4]
β
Constraints
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
π‘ Intuition
Unlike LeetCode 349 (where elements are unique in the result), here, the number of times an element appears in the result depends on the minimum count it appears in both arrays.
β
Solution 1: Hash Map with collections.Counter
Pythonβs Counter
makes it easy to track frequencies and find the intersection.
π Python Code
python
from collections import Counter
class Solution:
def intersect(self, nums1, nums2):
counts = Counter(nums1)
result = []
for num in nums2:
if counts[num] > 0:
result.append(num)
counts[num] -= 1
return result
π Step-by-Step Example
Input:
python
nums1 = [1, 2, 2, 1]
nums2 = [2, 2]
Step-by-step:
- Create a counter for
nums1
: {1: 2, 2: 2}
- Traverse
nums2
:
2
is in the counter β append 2
, decrement counter β now {1: 2, 2: 1}
2
again β append 2
, decrement counter β now {1: 2, 2: 0}
- Result:
[2, 2]
β±οΈ Time & Space Complexity
MetricComplexityTimeO(n + m)SpaceO(min(n, m))
β
Solution 2: Two-Pointer After Sorting
This works well if you are allowed to sort the input.
π Python Code
python
class Solution:
def intersect(self, nums1, nums2):
nums1.sort()
nums2.sort()
i = j = 0
result = []
while i < len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
result.append(nums1[i])
i += 1
j += 1
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return result
π§ Use Cases
- Comparing event logs with repeated entries
- Identifying shared transactions in two datasets
- Detecting common items with frequency caps
β
Conclusion
LeetCode 350: Intersection of Two Arrays II is a practical problem that helps you practice:
- Counting elements with dictionaries or
Counter
- Handling duplicates correctly
- Optimizing with sorting and two pointers
Choose the method that best fits the problem constraints β Counter for simplicity, or sorting for optimized space.