Return the intersection of two integer arrays, including duplicates as many times as they appear in both arrays.
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.
Compute the multiset intersection of the two arrays efficiently.
nums1 and nums2.nums1 and nums2 with duplicates preserved.0 <= nums1.length, nums2.lengthExample 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
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.