Two Pointers Merging sorted arrays
167. Intersection of Two Sorted Arrays
You are given two arrays of integers, nums1 and nums2, each sorted in non-decreasing order. Return their
intersection: the values that appear in both arrays, in non-decreasing order.
A repeated value counts as many times as it appears in both arrays. If a value appears three times in nums1
and twice in nums2, it appears twice in the answer. If no value appears in both, return an empty array.
Non-decreasing means that each element is greater than or equal to the one before it, so a value can appear more than once.
Example 1
Input: nums1 = [1, 2, 2, 2, 4, 7, 9]
nums2 = [2, 2, 3, 4, 4, 9, 10]
[2,2,4,9]Explanation: 2 appears three times in nums1 and twice in nums2, so it appears twice in the answer. 4 appears once in
nums1, so it appears once, and so does 9. The values 1, 3, 7 and 10 are in only one array.
Example 2
Input: nums1 = [-5, -1, 3, 8], nums2 = [-4, 0, 6]
[]Explanation: No value appears in both arrays, so the answer is empty.
Example 3
Input: nums1 = [-3, -3, 0, 8], nums2 = [-3, 0, 0, 8, 8]
[-3,0,8]Explanation: −3 appears twice in nums1 but once in nums2. 0 and 8 appear twice in nums2 but once in nums1. So each
of them appears once.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums1.length, nums2.length ≤ 105-109 ≤ nums1[i], nums2[j] ≤ 109- Both
nums1andnums2are sorted in non-decreasing order.
Clarifying questions
What you would ask an interviewer before writing any code.