Merge Sorted Array
You're given two arrays sorted in non-decreasing order, nums1 and nums2, and two integers m and n. The first m elements of nums1 are real values. Its last n slots hold 0 as placeholders, so nums1 has length m + n. nums2 has exactly n values.
Merge nums2 into nums1 so that nums1 ends up holding all m + n values in sorted order. Modify nums1 in place and don't return anything.
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]
The three zeros at the end of nums1 are space for the values from nums2.
Example 2
Input: nums1 = [0], m = 0, nums2 = [1], n = 1 Output: [1]
With m = 0, the 0 in nums1 is a placeholder, not a value.
Constraints
nums1.length == m + nnums2.length == n0 <= m, n <= 2001 <= m + n <= 200-10^9 <= nums1[i], nums2[j] <= 10^9
Approach
Copying nums2 into the empty slots and sorting works in O((m + n) log(m + n)) time, but it ignores that both arrays are already sorted. A standard merge from the front runs in linear time but needs a third array, because writing into the front of nums1 would overwrite values you haven't used yet.
Merge from the back instead. The largest value overall is the larger of nums1[m - 1] and nums2[n - 1], and it belongs in the last slot, which is free. Keep one pointer at the end of each array's real values and a write pointer at the end of nums1. At each step, copy the larger value to the write position and move that pointer left. The write pointer always stays at or ahead of the nums1 pointer, so nothing is overwritten before it's read.
Steps
- Set
i = m - 1,j = n - 1andwrite = m + n - 1. - While
j >= 0, comparenums1[i]andnums2[j](treatnums1as exhausted ifi < 0). - Copy the larger value to
nums1[write], then move that array's pointer andwriteone step left. - When
nums2runs out, stop. Whatever is left innums1is already in place.
from typing import List
def merge_sorted(nums1: List[int], m: int, nums2: List[int], n: int) -> None:
i, j = m - 1, n - 1 # last real value in each array
write = m + n - 1 # next slot to fill, from the back of nums1
while j >= 0:
if i >= 0 and nums1[i] > nums2[j]:
nums1[write] = nums1[i]
i -= 1
else:
nums1[write] = nums2[j]
j -= 1
write -= 1Complexity
- Time:
O(m + n). Each value is copied at most once. - Space:
O(1). The merge happens insidenums1.
Common mistakes
- Merging from the front and overwriting values of
nums1that haven't been compared yet. - Looping while
i >= 0 && j >= 0and forgetting to copy the rest ofnums2whennums1runs out first. - Treating the placeholder zeros as real values when
mis smaller than the array's length.