Merge Sorted Array

Merge nums2 into nums1 in place, filling from the back to avoid overwrites.

Easy
Time O(m + n) Space O(1)
LeetCode
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#

Merge Sorted Array
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--];
}
}
};

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#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.