Merge Sorted Array

Easy#88two arrays

You get two arrays sorted in ascending order. The first one ends with empty cells, exactly as many as there are numbers in the second. Merge the second array into the first, right inside it, so that the first stays sorted. Our example: [2, 5, 8, _, _, _] and [1, 6, 9] give [1, 2, 5, 6, 8, 9].

input
nums1: m integers in non-decreasing order, then n zeros, room for nums2; nums2: n integers in non-decreasing order.
returns
Nothing: change nums1 in place so that it holds all m + n numbers in non-decreasing order.
constraints
  • nums1.length = m + n, nums2.length = n
  • 0 ≤ m, n ≤ 200, 1 ≤ m + n ≤ 200
  • −10⁹ ≤ nums1[i], nums2[j] ≤ 10⁹
  • the first m of nums1 and all of nums2 are in non-decreasing order; the last n of nums1 are 0
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums1
 * @param {number} m
 * @param {number[]} nums2
 * @param {number} n
 * @return {void} Do not return anything, modify nums1 in-place instead.
 */
function merge(nums1, m, nums2, n) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more two pointers problems

Pattern “Two pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.