Merge Sorted Array

medium

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, along with two integers m and n giving how many real elements each holds.

Merge nums2 into nums1 so that nums1 becomes one sorted array. The merged result must be stored inside nums1: the function returns nothing.

To make room, nums1 has length m + n — its first m slots hold its real values, and the final n slots are 0 placeholders you may overwrite. nums2 has length n.

How your function is called

merge(nums1, m, nums2, n)   →   nothing; nums1 is mutated in place

The judge builds nums1 (the first m sorted values plus n trailing zeros) and nums2, calls your merge, then reads back the full nums1.

Hints

Both inputs are already sorted. What does that let you avoid doing to the combined result?
If you merge from the front, where do the elements you haven't read yet in nums1 get overwritten?
The free space is at the end of nums1. Fill it from the back, largest element first, using three pointers.

Common doubts

Merging front-to-back would overwrite nums1's own unprocessed values before you've placed them. The empty room is at the end, so filling from the back — largest first — never clobbers data you still need.
nums1 is already the answer — the loop places nothing and leaves it untouched.
nums1 has no real elements, so the result is exactly nums2 copied into nums1.

Interview follow-ups

Yes — the back-to-front three-pointer merge writes straight into nums1's spare room, using no auxiliary array.
Use a min-heap of the k front elements (or merge pairwise). That's the "merge k sorted lists" generalization, O(N log k).

Fun facts

  • Merging two sorted arrays in place is exactly the combine step of merge sort — done backward to reuse the destination's own free space.
  • Databases run this "sort-merge" step when joining two already-ordered inputs, spilling to disk from the back when memory is tight.

Asked at

AmazonMicrosoftMetaGoogleBloomberg
Frequently Sometimes Occasionally
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]
Merging [1,2,3] and [2,5,6] gives [1,2,2,3,5,6]. The result fills nums1.
Example 2
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
nums2 is empty, so nums1 is already the merged result.
Example 3
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
m = 0 means nums1 has no real elements; the answer is just nums2.
Constraints

- nums1.length == m + n - nums2.length == n - 0 <= m, n <= 200 - 1 <= m + n <= 400 - -10^9 <= nums1[i], nums2[j] <= 10^9 - nums1 (first m) and nums2 are each sorted in non-decreasing order.

Solve this problem →