easy +10 pts

Merge Sorted Array In Place

Merge two sorted arrays into the first array without extra space, maintaining sorted order.

You are given two integer arrays `nums1` and `nums2`, sorted in non-decreasing order. The first array `nums1` has a length of `m + n`, where the first `m` elements are the elements to be merged, and the last `n` elements are set to 0 and should be ignored. The second array `nums2` has a length of `n`. Implement a function `merge(nums1, m, nums2, n)` that merges `nums2` into `nums1` in-place so that the first `m + n` elements of `nums1` contain all elements in sorted non-decreasing order. The function should return the merged `nums1` list (returning the same list object is acceptable). Since the list is modified in-place, the caller can also just inspect `nums1`, but returning the list helps the test harness.

Constraints

- `nums1.length == m + n` - `nums2.length == n` - `0 <= m, n <= 200` - `1 <= m + n <= 200` - `-10^9 <= nums1[i], nums2[j] <= 10^9` - Both arrays are sorted in non-decreasing order. - You must do this in-place with O(1) extra space. Time complexity O(m + n) is expected.

Example

>>> nums1 = [1,2,3,0,0,0]
>>> m = 3
>>> nums2 = [2,5,6]
>>> n = 3
>>> result = merge(nums1, m, nums2, n)
>>> result
[1,2,2,3,5,6]

>>> nums1 = [1]
>>> m = 1
>>> nums2 = []
>>> n = 0
>>> merge(nums1, m, nums2, n)
[1]

>>> nums1 = [0]
>>> m = 0
>>> nums2 = [1]
>>> n = 1
>>> merge(nums1, m, nums2, n)
[1]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Work backwards from the end of both arrays to avoid overwriting elements in nums1.
Keep three pointers: one for the last position of the filled part of nums1, one for the last element of the first m elements of nums1, and one for the last element of nums2.
After processing, if there are leftover elements in nums2, copy them directly into the front of nums1.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.