Merge two sorted arrays into the first one in place: fill from the back, always placing the larger tail, so nothing gets overwritten.
▼The problem
LeetCode 88 (Easy). nums1 has length m + n: its first m values are sorted, the last n slots are empty (zeros). nums2 holds n sorted values. Merge nums2 into nums1 in place so that nums1 is sorted.
Example (LeetCode's example 1, animated throughout): nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 → [1,2,2,3,5,6].
def merge(nums1, m, nums2, n):
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 -= 1TRY IT ON LEETCODE ▶The solution
def merge(nums1, m, nums2, n):
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 -= 1Transcript
Merge Sorted Array. You get two sorted arrays. The first has m values, then n empty slots at the end, room for the second's n values. Merge the second into the first, in place, so it ends up sorted.
Here, the first holds one, two, three, then three empty slots. The second holds two, five, six. Merged, the first should read one, two, two, three, five, six.
The easy way: copy the second array into the gap, then sort. But sorting costs m plus n, times log of m plus n. Merging from the front is linear, but there's a catch: the second's two lands on the three before we've read it. To save it, you'd shift everything right, or copy the first array out.
So merge from the back, where the empty slots are. Point i at the first array's last value, j at the second's, and k at the last slot. Compare the two, and put the larger at k. Then step that pointer and k one to the left.
Why is that safe? k always stays j plus one slots ahead of i. While j has values, that's at least one, so nothing unread gets overwritten.
In code: set the three pointers, and loop while j has values. If the first array's value is larger, copy it to k and step i. Otherwise, copy the second's and step j. Either way, step k. If i runs out first, the second array just fills the front.
Let's walk it. Three against six: six parks in the last slot. Three against five: five goes next. Three against two: now three is larger and moves back. Two against two is a tie, so we take the second's two. Now j is done, so we stop. One and two were already in place.
Every step fills one slot from the back, so the time is order m plus n. And the extra space is order one: just three pointers.
Fill from the back, take the larger, never overwrite. That's Merge Sorted Array.