Return the intersection of two integer arrays, including duplicates as many times as they appear in both arrays.
Problem
Given two integer arrays, build an array containing every value that appears in both arrays. If a number occurs multiple times in both arrays, include it in the result the minimum number of times it appears in either array.
The order of elements in the returned array does not matter.
Goal
Compute the multiset intersection of the two arrays efficiently.
Notes
- A value can appear more than once in the output if it appears more than once in both inputs.
- You may return the result in any order unless a specific platform variant requires otherwise.
Input Format
- Two integer arrays
nums1andnums2. - Each array may contain duplicate values.
- No additional special input structure is required.
Output Format
- Return an integer array containing the intersection of
nums1andnums2with duplicates preserved. - Any order is acceptable.
Constraints
0 <= nums1.length, nums2.length- Array values are integers.
- The solution should be efficient for large inputs; an or approach is typically expected.
Example 1
Input
nums1 = [1,2,2,1], nums2 = [2,2]
Output
[2,2]
Explanation
The value 2 appears twice in both arrays, so it is included twice in the result.
Example 2
Input
nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output
[4,9]
Explanation
Both 4 and 9 appear in each array. Each is included once because that is the minimum frequency across the two arrays.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.