Skip to problem
←

Merge Sorted Array

Easy 0 attempts

You're given two arrays, nums1 and nums2, both already sorted in non-decreasing order, along with integers m and n telling you how many actual elements each array holds. The first m entries of nums1 are valid data, followed by n reserved slots; all n entries of nums2 are valid. Combine them into one sorted array, writing the result directly back into nums1 rather than returning a new array.

Only indices determine which entries are valid: a 0 within the first m positions is real data and must be preserved. The final n slots are placeholders, not additional values to merge. Either valid input portion may be empty.

Function contract

Implement merge(nums1, m, nums2, n).

Output: Modify nums1 in place to contain all m + n values in non-decreasing order. Return nothing; the runner checks nums1 and ignores the return value.

Example 1

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

Example 2

Input
nums1 = [0]
m = 0
nums2 = [1]
n = 1
Output
[1]
Constraints
  • nums1.length == m + n; nums2.length == n
  • 0 <= m, n <= 200; m + n >= 1
  • Valid portions of both arrays are sorted in non-decreasing order.
  • -10^9 <= nums1[i], nums2[j] <= 10^9

Use three pointers starting from the end of both arrays and the end of nums1. Fill nums1 from the back by comparing elements, which avoids overwriting elements that still need to be processed.

If nums2 still has values after nums1’s valid prefix is exhausted, copy them into the remaining positions. Any values left in nums1 are already in place, so no second copy loop is needed for them.

javascript
function merge(nums1, m, nums2, n) {
  let i = m - 1, j = n - 1, k = m + n - 1;

  while (i >= 0 && j >= 0) {
    if (nums1[i] > nums2[j]) {
      nums1[k--] = nums1[i--];
    } else {
      nums1[k--] = nums2[j--];
    }
  }

  while (j >= 0) {
    nums1[k--] = nums2[j--];
  }
}

Time: O(m + n) Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript