Skip to content
CodeShare
All problems

Merge Sorted Array

Merge one sorted array into another, in place.

EasyArraysTwo pointersSorting

You're given two sorted arrays, nums1 and nums2, and two numbers: m, how many real values are in nums1, and n, the length of nums2. nums1 has room for both: its last n slots are zeros waiting to be filled.

Merge nums2 into nums1 in place, so that nums1 ends up as one sorted array. The tests check nums1 after your function finishes.

Examples

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 = [1], m = 1, nums2 = [], n = 0
Output
[1]
Why
There's nothing to merge.
Example 3
Input
nums1 = [0], m = 0, nums2 = [1], n = 1
Output
[1]
Why
nums1 has no real values yet, so it ends up holding nums2.

Constraints

  • nums1.length == m + n
  • nums2.length == n
  • 0 <= m, n <= 200
  • -10^9 <= nums1[i], nums2[j] <= 10^9