DSA problem
Intersection of Two Arrays II
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.
Unlike the basic intersection problem where duplicates are collapsed, here multiplicity matters: if a value appears 2 times in nums1 and 3 times in nums2, it should appear exactly 2 times (the minimum) in the output.
Follow-up questions worth considering: What if the arrays are already sorted? How would you optimize the algorithm then? What if nums1's size is small compared to nums2's size? What if elements of nums2 are stored on disk and memory is limited so you cannot load all elements into memory at once?
Examples
nums1 = [1,2,2,1], nums2 = [2,2][2,2]nums1 = [4,9,5], nums2 = [9,4,9,8,4][4,9]nums1 = [1,2], nums2 = [1,1][1]Constraints
- 1 <= nums1.length, nums2.length <= 1000
- 0 <= nums1[i], nums2[i] <= 1000
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.