Home
DSA Patterns
Two Pointers
Merge Sorted Array
Merge Sorted Array
Merge two sorted arrays in place in O(m + n) by filling nums1 from the back with three pointers.
Problem Understanding
Merge Sorted Array: nums1 holds m sorted values followed by n zeros of room, and nums2 holds n sorted values. Merge nums2 into nums1 in place so nums1 ends up sorted.
Example: nums1 = [1, 2, 3, 0, 0, 0], m = 3, nums2 = [2, 5, 6], n = 3 becomes [1, 2, 2, 3, 5, 6].
The Intuition: The Free Space Is at the End
Merging from the front, as in Merge Two Sorted Lists, would overwrite nums1 values before they are placed. But the free room is at the end, and the end of the merged array holds the largest values. So merge backwards with two pointers and a write pointer:
iat the last realnums1value,jat the lastnums2value,kat the last slot.- Write the larger of
nums1[i]andnums2[j]tok, and move that pointer andkleft. - Stop when
j < 0: whatever is left innums1is already in place.
k never passes i, because k − i = j + 1 > 0 while nums2 values remain, so nothing is overwritten too early.
Interactive Walkthrough
nums1's empty room is drawn dashed. Each step writes the larger of nums1[i] and nums2[j] into slot k, filling from the right. Watch the loop stop as soon as nums2 is used up.
Dry Run Table
Input: nums1 = [1, 2, 3, _, _, _], nums2 = [2, 5, 6]
| i | j | k | Compare | Write |
|---|---|---|---|---|
| 2 | 2 | 5 | 3 vs 6 | 6 |
| 2 | 1 | 4 | 3 vs 5 | 5 |
| 2 | 0 | 3 | 3 vs 2 | 3 |
| 1 | 0 | 2 | 2 vs 2 | 2 (from nums2) |
| 1 | −1 | 1 | — | stop |
Result: [1, 2, 2, 3, 5, 6].
The Solution Template
Three pointers, merging from the back.
Merge Sorted Array Code
1var merge = function(nums1, m, nums2, n) {2 let i = m - 1, j = n - 1, k = m + n - 1;3 while (j >= 0) {4 if (i >= 0 && nums1[i] > nums2[j]) nums1[k--] = nums1[i--];5 else nums1[k--] = nums2[j--];6 }7};
Edge Cases & Common Mistakes
- n = 0: nothing to merge; the loop never runs.
- m = 0: every value comes from nums2; the
i ≥ 0check stops you reading nums1[−1]. - Looping while i ≥ 0 instead of j ≥ 0: leftover nums2 values would never be copied.
- Merging from the front: overwrites nums1 values that have not been placed yet.
Summary
nums1's free room is at the end, so merge backwards: compare the largest unplaced values of both arrays and write the larger to the last free slot. Stop when nums2 is used up. O(m + n) time, O(1) extra space.
More practice: DSA interview questions with answers · patterns cheat sheet
