Coding Interview PatternsMerge Sorted Array
EasyK-way Merge
Merge Sorted Array
Explanation & Solution
Description
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums2 into nums1 as one sorted array in-place. nums1 has a length of m + n, where the last n elements are set to 0 and should be ignored.
Input:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
0
1
1
2
2
3
3
0
4
0
5
0
0
2
1
5
2
6
Output:[1,2,2,3,5,6]
0
1
1
2
2
2
3
3
4
5
5
6
Explanation: The arrays are merged into [1,2,2,3,5,6].
Constraints
nums1.length == m + nnums2.length == n0 <= m, n <= 200-10^9 <= nums1[i], nums2[j] <= 10^9
Approach
K-way Merge pattern
1. Use Three Pointers From the End
p1starts at the last valid element ofnums1(indexm - 1)p2starts at the last element ofnums2(indexn - 1)pis the write pointer starting at the last position ofnums1(indexm + n - 1)- Writing from the back avoids overwriting elements we still need
2. Fill From Largest to Smallest
- While
p2 >= 0, comparenums1[p1]andnums2[p2] - Place the larger value at
nums1[p]and move both the chosen source pointer andpbackward - If
nums1is exhausted (p1 < 0), keep copying fromnums2
3. Remaining Elements
- If
p1still has elements whenp2is exhausted, they are already in place — no work needed - If
p2still has elements, theelsebranch copies them
Key Insight
- The key insight is to iterate backwards so we use the spare space without clobbering unprocessed elements
Time
O(m + n)each element is written exactly onceSpace
O(1)no extra array; we write into the trailing zeros of `nums1`Visualization
Input:
[1, 2, 3, 0, 0, 0], m = 3
—
No animation available
Left (L)Right (R)ConvergedDone
0 steps