codejump
EasyPythonJavaScriptTypeScript

Sorting — Merge Sorted Array In Place

AlgorithmsSortingTwo Pointers

solve(nums1, m, nums2, n) — nums1 has length m + n: its first m values are
sorted and the last n slots are padding (zeros). nums2 holds n sorted values.
Merge nums2 into nums1 so that nums1 is sorted, and return nums1.

Fill nums1 from the back: the largest remaining value always belongs at the
end, and writing there never overwrites a value you still need.

Examples

solve([1,2,3,0,0,0], 3, [2,5,6], 3)  → [1,2,2,3,5,6]
solve([1], 1, [], 0)                 → [1]
solve([0], 0, [1], 1)                → [1]

Sample tests

Test #1Interleaved values
Input: [[1,2,3,0,0,0],3,[2,5,6],3]
Output: [1,2,2,3,5,6]
Test #2Nothing to merge
Input: [[1],1,[],0]
Output: [1]
Test #3nums1 is only padding
Input: [[0],0,[1],1]
Output: [1]