Merge Sorted Arrays
Problem Statement
You are given two sorted arrays nums1 and nums2. Merge nums2 into nums1 as one sorted array, modifying nums1 in-place.
nums1 has enough space at the end to hold all elements from nums2. The parameter m represents the number of valid elements in nums1, and n represents the number of elements in nums2.
Function Signature:
function merge(nums1, m, nums2, n) {
// Your code here
}
Examples
| nums1 | m | nums2 | n | Result |
|---|---|---|---|---|
[1, 2, 3, 0, 0, 0] | 3 | [2, 5, 6] | 3 | [1, 2, 2, 3, 5, 6] |
[1] | 1 | [] | 0 | [1] |
[0] | 0 | [1] | 1 | [1] |
Constraints
- nums1.length = m + n
- nums2.length = n
- 0 ≤ m, n ≤ 200
- -10⁹ ≤ nums1[i], nums2[j] ≤ 10⁹
- Both arrays are sorted in ascending order
Interactive Editor
function merge(nums1, m, nums2, n) { // Your code here }
Hints
Hint 1: Direction Matters
If you merge from the beginning, you risk overwriting elements in nums1 that you haven't processed yet. Consider merging from the end instead, where the empty space is.
Hint 2: Three Pointers
Use three pointers:
p1pointing to the last valid element innums1(indexm - 1)p2pointing to the last element innums2(indexn - 1)writeIndexpointing to the last position innums1(indexm + n - 1)
Compare elements at p1 and p2, place the larger one at writeIndex, then move the appropriate pointers.
Hint 3: When to Stop
You only need to continue while p2 >= 0. If p2 becomes negative first, the remaining elements in nums1 are already in their correct positions. But if p1 becomes negative first, you still need to copy remaining elements from nums2.
Solution
View Solution Explanation
function merge(nums1, m, nums2, n) {
let p1 = m - 1; // Last valid element in nums1
let p2 = n - 1; // Last element in nums2
let writeIndex = m + n - 1; // Last position in nums1
while (p2 >= 0) {
if (p1 >= 0 && nums1[p1] > nums2[p2]) {
nums1[writeIndex] = nums1[p1];
p1--;
} else {
nums1[writeIndex] = nums2[p2];
p2--;
}
writeIndex--;
}
return nums1;
}
Why Merge from the End?
The key insight is that nums1 has empty space at the end, not the beginning. If we merge from the start, we'd overwrite elements we still need. By merging from the end, we fill the empty space first.
How It Works
- Start all three pointers at the end of their respective regions
- Compare
nums1[p1]andnums2[p2]}, place the larger value atwriteIndex - Move the pointer of whichever element we just placed, and move
writeIndex - Continue until we've placed all elements from
nums2
Why Only Check p2 >= 0?
If p2 goes negative first, all of nums2 is merged and nums1's remaining elements are already in place.
If p1 goes negative first, the condition p1 >= 0 && nums1[p1] > nums2[p2] fails, so we copy from nums2, which is correct.
Complexity: O(m + n) time, O(1) space.