Merge Sorted Array
Merge one sorted array into another that has empty room at its end, so the result stays sorted.
You are given two integer arrays, nums1nums2mnums1nnums2nums1mnnums2nums1m + nnums1
Example 1
Output: [1, 2, 2, 3, 5, 6]
Example 2
Output: [1]
The Idea
Think of two stacks of marked exams, each already sorted by score, that have to become one sorted stack. You look at the top exam of each stack, take the one that comes first, and repeat until both stacks are empty. Merging two sorted arrays works the same way. The twist here is where the result goes: into nums1
Look at Example 1. In nums1 = [1, 2, 3, 0, 0, 0]nums2 = [2, 5, 6]nums1nums2nums1
So where is there room to write without losing anything? At the back. The largest value of all belongs in the last slot, and the last slot is free. Because both arrays are sorted, that largest value is the larger of their last values: the 3 at the end of the real values of nums1nums2
That gives a way to merge from the back. Keep three markers: inums1jnums2knums1ijk
In row 1, ijkjkjnums2nums1i
Row 4 is the interesting one. knums2nums2nums1
So filling from the back, the slot being written is always free or holds a value that has already moved. Walking markers along arrays like this, instead of comparing every value with every other one, is called the two-pointer technique, and here it runs with two arrays.
Solution Approach
Turning the merge from the back into code means settling three things: where to write, when the loop can stop, and what happens when nums1
Where to write
Why not something simpler? One way is to copy nums2nums1
Is it really safe, though? Can kinums1km + n - 1i + j + 1kijki + j + 1nums2jki
When to stop
When is the merge finished? As soon as nums2jkinums1
When nums1 runs out first
What if every real value of nums1nums2inums1[i]inums2m = 0i
Java Solution
The method merge
- First, set
toi , the last real value ofm - 1 , andnums1 toj , the last value ofn - 1 .nums2 - Fill the slots with a
loop:for starts at the last slot,k , moves one place left each pass, and the loop runs whilem + n - 1 is 0 or more.j - In each pass, if
is 0 or more andi is larger thannums1[i] , copynums2[j] to slotnums1[i] and movek left. Otherwise copyi there and movenums2[j] left, which is also what happens when the two values are equal.j - When the loop ends,
holds the merged values, so the method has nothing to return.nums1
The mainnums1nums2nums2
import java.util.Arrays;
public class MergeSortedArray {
public static void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1; // last real value of nums1
int j = n - 1; // last value of nums2
for (int k = m + n - 1; j >= 0; k--) { // fill from the back
if (i >= 0 && nums1[i] > nums2[j]) {
nums1[k] = nums1[i--];
} else {
nums1[k] = nums2[j--];
}
}
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 0, 0, 0};
merge(a, 3, new int[] {2, 5, 6}, 3);
System.out.println(Arrays.toString(a));
int[] b = {0};
merge(b, 0, new int[] {1}, 1);
System.out.println(Arrays.toString(b));
int[] c = {4, 5, 6, 0, 0, 0};
merge(c, 3, new int[] {1, 2, 3}, 3);
System.out.println(Arrays.toString(c));
int[] d = {1, 2, 3};
merge(d, 3, new int[] {}, 0);
System.out.println(Arrays.toString(d));
int[] e = {-3, 0, 0, 7, 0, 0, 0};
merge(e, 4, new int[] {-5, 0, 9}, 3);
System.out.println(Arrays.toString(e));
}
}
Running it prints:
[1, 2, 2, 3, 5, 6]
[1]
[1, 2, 3, 4, 5, 6]
[1, 2, 3]
[-5, -3, 0, 0, 0, 7, 9]
[1, 2, 2, 3, 5, 6][1]inums2
Look at the third line, [1, 2, 3, 4, 5, 6][4, 5, 6][1, 2, 3]nums1ij[4, 5, 6, 4, 5, 6]
The fourth line, [1, 2, 3]nums2jm = 4nums1nums2
The original implementation,
Complexity
Each pass of the loop writes one slot of nums1
- Time: O(m + n).
moves one slot left per pass and starts at the last of the m + n slots, so there are at most m + n passes.k - Space: O(1). The values move inside
itself, and the only extra storage is the three markersnums1 ,i andj .k
The same comparison of two sorted runs is the merge step of