Merge Two Sorted Arrays Into the First Array In Place

Implement mergeSortedArrays

You're given two sorted arrays, nums1 and nums2, and two counts m and n telling you how many real values sit at the front of each. nums1 is deliberately longer than its real content — it has exactly n extra slots at the end, reserved so nums2's values can be folded straight into it. Merge nums2 into nums1 so that the first m + n positions hold every value from both arrays in non-decreasing order. Try to avoid allocating a second array the size of the result — filling nums1 from the back, largest values first, means you never overwrite a value before you've had a chance to read it.

Example 1:

Input: nums1 = [1,4,7,0,0,0], m = 3, nums2 = [2,3,9], n = 3

Output: [1,2,3,4,7,9]

Example 2:

Input: nums1 = [5,0], m = 1, nums2 = [2], n = 1

Output: [2,5]

Example 3:

Input: nums1 = [0,0,0], m = 0, nums2 = [1,2,6], n = 3

Output: [1,2,6]

+ 5 hidden test cases run on Submit.

Constraints:

  • 1 ≤ m, n ≤ 200
  • nums1.length == m + n
  • nums2.length == n
  • -10⁹ ≤ nums1[i], nums2[j] ≤ 10⁹
  • Both nums1's first m entries and all of nums2 are sorted in non-decreasing order

nums1 =

[1, 4, 7, 0, 0, 0]

m =

3

nums2 =

[2, 3, 9]

n =

3