Two Pointers Merging sorted arrays
169. Merge Two Sorted Arrays Without Extra Space
You are given two arrays of integers, nums1 with n elements and nums2 with m elements. Each one is
sorted in non-decreasing order.
Move values between the two arrays so that nums1 followed by nums2 reads as one sorted sequence. In the
end nums1 holds the n smallest values in non-decreasing order, and nums2 holds the other m values in
non-decreasing order. Neither array changes its length.
Change both arrays in place, using only O(1) extra memory: no third array. The function returns nothing. The
output shows both arrays after the call, as [nums1,nums2].
Example 1
Input: nums1 = [1, 4, 8, 10], nums2 = [2, 3, 9]
[[1,2,3,4],[8,9,10]]Explanation: Together the arrays hold 1, 2, 3, 4, 8, 9 and 10. The four smallest stay in nums1, so 2 and 3 move in
and 8 and 10 move out to nums2.
Example 2
Input: nums1 = [-5, 0, 0], nums2 = [-7, 0]
[[-7,-5,0],[0,0]]Explanation: −7 is the smallest value, so it moves to the front of nums1, and one 0 moves to nums2. The 0s are
equal, so it does not matter which one moves.
Example 3
Input: nums1 = [2, 3], nums2 = [3, 7, 11]
[[2,3],[3,7,11]]Explanation: No value of nums1 is bigger than any value of nums2, so nothing moves.
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[i] ≤ 109nums1andnums2are each sorted in non-decreasing order.
Clarifying questions
What you would ask an interviewer before writing any code.