Skip to content

Merge Sorted Array

EasyTwo Pointers
Decode it first. Clues, constraints, pattern and plan before any code.

You are given two lists sorted in non-decreasing order, nums1 and nums2, and two counts m and n. The first m values of nums1 are real; its last n slots are placeholders (zeros) with room for nums2. nums2 holds exactly n values.

Merge nums2 into nums1 in place so that nums1 becomes one sorted list of length m + n. Do not return anything.

nums1 = [1, 2, 3, 0, 0, 0], m = 3, nums2 = [2, 5, 6], n = 3   →  nums1 becomes [1, 2, 2, 3, 5, 6]
nums1 = [1], m = 1, nums2 = [], n = 0                         →  nums1 stays [1]
nums1 = [0], m = 0, nums2 = [1], n = 1                        →  nums1 becomes [1]

Constraints

  • nums1.length == m + n
  • nums2.length == n
  • 0 <= m, n <= 200 and 1 <= m + n <= 200
  • -10^9 <= nums1[i], nums2[j] <= 10^9
  • Aim for O(m + n) time.