Loading content...
Given two integer arrays, determine the elements that appear in both arrays while preserving their frequency of occurrence. Each element in the result should appear exactly as many times as it occurs in both arrays — that is, if an element appears m times in the first array and n times in the second array, it should appear min(m, n) times in the output.
You may return the result in any order. The solution must account for duplicate values correctly, ensuring that the frequency of each common element in the output reflects the minimum count across both input arrays.
Core Concept: This problem requires you to find the multiset intersection of two arrays — not just the set intersection where duplicates are ignored, but a proper intersection that respects element multiplicities.
nums1 = [1,2,2,1]
nums2 = [2,2][2,2]The element 2 appears twice in nums1 and twice in nums2. The minimum frequency is min(2, 2) = 2, so we include 2 twice in the result. Element 1 appears in nums1 but not in nums2, so it is excluded.
nums1 = [4,9,5]
nums2 = [9,4,9,8,4][4,9]Element 4 appears once in nums1 and twice in nums2, so it appears min(1, 2) = 1 time. Element 9 appears once in nums1 and twice in nums2, so it appears min(1, 2) = 1 time. Elements 5 and 8 are unique to their respective arrays. Note: [9,4] is also a valid output.
nums1 = [1,2,3]
nums2 = [3,2,1][1,2,3]All elements 1, 2, and 3 appear exactly once in both arrays. The intersection includes each element once. Any permutation like [2,1,3] or [3,1,2] is also valid.
Constraints