Merge two sorted arrays into nums1 in-place without using extra space.
Problem Statement
Examples
Input: nums1 = [1, 2, 3, 0, 0, 0], m = 3, nums2 = [2, 5, 6], n = 3
Output: [1, 2, 2, 3, 5, 6]
Explanation: Combining the input according to Merge two sorted arrays without extra space logic yields [1, 2, 2, 3, 5, 6].
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: Combining the input according to Merge two sorted arrays without extra space logic yields [1].
Complexity
Time Complexity: O(M + N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
Merging from the beginning would overwrite unprocessed elements in nums1. By merging from the back (index m + n - 1), we write to currently empty space, achieving O(M + N) time with O(1) extra space.
Step-by-Step Approach
- Set
p1 = m - 1,p2 = n - 1, and write pointerp = m + n - 1. - While
p1 >= 0 && p2 >= 0, place the larger ofnums1[p1]andnums2[p2]intonums1[p]and decrement. - Drain remaining elements of
nums2intonums1. - Return
nums1.
Optimal Implementation (JavaScript)
function mergeSortedArrays(nums1, m, nums2, n) {
let p1 = m - 1, p2 = n - 1, p = m + n - 1;
while (p1 >= 0 && p2 >= 0) {
if (nums1[p1] > nums2[p2]) {
nums1[p] = nums1[p1--];
} else {
nums1[p] = nums2[p2--];
}
p--;
}
while (p2 >= 0) nums1[p--] = nums2[p2--];
return nums1;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- m = 0: nums1 filled entirely from nums2.
- n = 0: nums1 remains unchanged.