Merge Sorted Array
Merge Sorted Array is LeetCode 88 (Easy). You get two arrays sorted in non-decreasing order:
nums1has lengthm + n. Its firstmvalues are real; the lastnplaces are zeros that only reserve space.nums2holdsnvalues.
Merge nums2 into nums1 so that nums1 becomes one sorted array of m + n values. Nothing is returned; the result must be written in place inside nums1. The follow-up asks for O(m + n) time.
- nums1.length == m + n
- nums2.length == n
- 0 <= m, n <= 200
- 1 <= m + n <= 200
- -10⁹ <= nums1[i], nums2[j] <= 10⁹
Intuition
To merge two sorted arrays you repeatedly pick the next value from the front of one of them. Doing that from the left here would overwrite nums1 values you have not read yet. The empty space sits at the right end, so fill nums1 from the back with the largest value left.
- Which value is largest: it is either the last unplaced value of nums1 or the last unplaced value of nums2.
- Why nothing is lost: while nums2 still has
j + 1values to place, the write slot is exactlyj + 1places right of the last unread nums1 value. The write position can never reach a value you still need.
An in-place merge where the spare room sits at one end of the target array. Fill from the end that has the room, and every write lands on space that is already free.
Approach
Before reading on, decide which value must end up in the very last slot of nums1, and where it can come from. Then check what happens when one array runs out first. Aim for O(m + n) time and no extra array.
Point at the three right ends
Set i = m - 1 (last real value of nums1), j = n - 1 (last value of nums2) and k = m + n - 1 (last slot). The largest unplaced value always belongs in slot k.
Move the larger value to slot k
If i >= 0 and nums1[i] > nums2[j], copy nums1[i] into slot k and move i left. Otherwise copy nums2[j] and move j left. Then move k left, because that slot is now final.
Stop when nums2 is used up
Loop while j >= 0. Once every nums2 value is placed, the nums1 values still unmoved are its smallest ones, already sorted and already in slots 0 to i, so no more work is needed.
Why the write never overwrites
Each step places one value, so k - i always equals the number of nums2 values still waiting, j + 1. That count is at least 1 inside the loop, so slot k is always to the right of every unread nums1 value.
Code in Python, C++ and Java
Common pitfalls
Merging from the front
i = j = k = 0 # write the smaller of nums1[i], nums2[j] to nums1[k]
i, j, k = m - 1, n - 1, m + n - 1 # write the larger to nums1[k], moving left
With nums1 = [1, 2, 3, 0, 0, 0] and nums2 = [2, 5, 6], the third write puts nums2's 2 into slot 2 and destroys the 3 before it is read. The front of nums1 is full; only the back is free.
Looping only while both arrays have values
while i >= 0 and j >= 0:
while j >= 0:
With nums1 = [4, 5, 6, 0, 0, 0] and nums2 = [1, 2, 3], nums1 runs out after three moves and the loop stops, leaving [4, 5, 6, 4, 5, 6]. The values 1, 2 and 3 are never copied.
Dropping the i >= 0 check
if nums1[i] > nums2[j]:
if i >= 0 and nums1[i] > nums2[j]:
With nums1 = [2, 0], m = 1 and nums2 = [1], i becomes -1 after the 2 moves right. Python then reads nums1[-1], the 2 just written, copies it again and soon raises an IndexError; C++ and Java read outside the array.
Edge cases
n = 0j starts at -1, so the loop never runs and nums1 stays as it is.
m = 0i starts at -1, so every step takes the nums2 branch and copies nums2 into nums1 in order.
Complexity
Merge Sorted Array FAQ
Why not copy nums2 into the empty slots and sort?
It works and is short, but sorting costs O((m + n) log(m + n)). It ignores the fact that both inputs are already sorted, which is what makes the linear merge possible.
What if nums1 has no empty slots at the end?
That is a different problem, often called merging without extra space: the smallest values must end up in the first array and the rest in the second. Filling from the back no longer works, and the usual answers are the gap method or swapping across the two arrays and re-sorting.