Merge Sorted Array
Merge nums2 into nums1 in place, filling from the back to avoid overwrites.
3 min read
k-way-merge two-pointers
Problem#
nums1 has length m + n with the first m elements sorted; the remaining n slots are zeros (placeholders). nums2 has n sorted elements. Merge nums2 into nums1 in place.
Examples#
nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3→[1,2,2,3,5,6]
Constraints#
0 <= m, n <= 200.
Approach#
Fill from the back. Three pointers: i = m-1 (top of nums1), j = n-1 (top of nums2), k = m+n-1 (write position). At each step, place the larger of nums1[i] and nums2[j] at nums1[k] and step both down.
Solution#
class Solution {public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int i = m - 1, j = n - 1, k = m + n - 1; while (j >= 0) { if (i >= 0 && nums1[i] > nums2[j]) nums1[k--] = nums1[i--]; else nums1[k--] = nums2[j--]; } }};func merge(nums1 []int, m int, nums2 []int, n int) { i, j, k := m-1, n-1, m+n-1 for j >= 0 { if i >= 0 && nums1[i] > nums2[j] { nums1[k] = nums1[i] i-- } else { nums1[k] = nums2[j] j-- } k-- }}from typing import List
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: i, j, k = m - 1, n - 1, m + n - 1 while j >= 0: if i >= 0 and nums1[i] > nums2[j]: nums1[k] = nums1[i] i -= 1 else: nums1[k] = nums2[j] j -= 1 k -= 1function merge(nums1, m, nums2, n) { let i = m - 1, j = n - 1, k = m + n - 1; while (j >= 0) { if (i >= 0 && nums1[i] > nums2[j]) { nums1[k] = nums1[i]; i--; } else { nums1[k] = nums2[j]; j--; } k--; }}class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int i = m - 1, j = n - 1, k = m + n - 1; while (j >= 0) { if (i >= 0 && nums1[i] > nums2[j]) { nums1[k--] = nums1[i--]; } else { nums1[k--] = nums2[j--]; } } }}function merge(nums1: number[], m: number, nums2: number[], n: number): void { let i = m - 1, j = n - 1, k = m + n - 1; while (j >= 0) { if (i >= 0 && nums1[i] > nums2[j]) { nums1[k] = nums1[i]; i--; } else { nums1[k] = nums2[j]; j--; } k--; }}Editorial#
Filling from the back avoids overwriting unread positions — the write pointer is always at or past the read pointers. We only need to keep walking until j < 0; if i runs out first, the remaining nums2 elements naturally settle into the front slots.
Complexity#
- Time: O(m + n).
- Space: O(1).
Concept revision#
Related#