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, nums1 and nums2, each sorted from small to large (equal values may repeat). You are also given m, the number of real values in nums1, and n, the length of nums2. nums1 has room for both: its first m slots hold its values, and its last n slots hold zeros that only reserve space. Move the values of nums2 into nums1 so that all m + n values end up there, sorted. The method returns nothing; nums1 itself holds the answer.

Example 1
Input: nums1 = [1, 2, 3, 0, 0, 0], m = 3, nums2 = [2, 5, 6], n = 3
Output: [1, 2, 2, 3, 5, 6]
Example 2
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Solution

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, which already holds values of its own.

Look at Example 1. In nums1 = [1, 2, 3, 0, 0, 0], the real values are 1, 2 and 3, and the three zeros are just room for nums2 = [2, 5, 6]. Start from the front, smallest value first. The 1 and the 2 of nums1 are already in slots 0 and 1. The next smallest value is the 2 of nums2, and it belongs in slot 2. But slot 2 holds the 3 of nums1, which has not been placed yet. Writing the 2 there would lose the 3.

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 nums1, or the 6 at the end of nums2.

That gives a way to merge from the back. Keep three markers: i on the last value of nums1 not yet placed, j on the last value of nums2 not yet placed, and k on the slot of nums1 being filled. Each time, the larger of the values at i and j goes to slot k. Look at the picture below.

Merging nums2 = [2, 5, 6] into nums1 = [1, 2, 3, _, _, _] from the back, in four rows. Row 1: 3 against 6, so 6 goes to slot 5. Row 2: 3 against 5, so 5 goes to slot 4. Row 3: 3 against 2, so 3 goes to slot 3. Row 4: 2 against 2, so the 2 of nums2 goes to slot 2. Then nums2 is used up and nums1 reads 1, 2, 2, 3, 5, 6.

In row 1, i is on the 3, j on the 6, and k on the empty slot 5. The 6 is larger, so it goes to slot 5, and j and k move one place left. In row 2, the 5 beats the 3 and fills slot 4. In row 3, j is on the 2 of nums2, so this time the 3 of nums1 is larger and moves to slot 3, and i moves left.

Row 4 is the interesting one. k is on slot 2, which still shows a 3. That is only an old copy: the 3 already moved to slot 3, so writing over it loses nothing. Both markers point at a 2, and the 2 of nums2 goes to slot 2. Now nums2 is used up, and the 1 and 2 at the front of nums1 were in their places all along, as the last row shows.

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 runs out of values first.

Where to write

Why not something simpler? One way is to copy nums2 into the free slots and sort the whole array. That works, but sorting does more work than one pass, about (m + n) log(m + n) steps, and ignores that both arrays were sorted already. Another way is to copy the real values of nums1 into a new array and merge from the front. That takes one pass, but needs room for m extra values. Merging from the back needs neither.

Is it really safe, though? Can k ever catch up with i and overwrite a value of nums1 that has not moved yet? At the start, k is m + n - 1, which is i + j + 1. Each step moves k left by one, and also moves exactly one of i or j left by one. So k stays equal to i + j + 1, and while nums2 still has values (j is 0 or more), k is to the right of i.

When to stop

When is the merge finished? As soon as nums2 is used up, so the loop runs while j is 0 or more. At that moment k equals i, so the values of nums1 that never moved are already in their own slots, as the 1 and 2 were in the picture. Nothing needs copying.

When nums1 runs out first

What if every real value of nums1 has moved but nums2 still has some? Then i is -1, and reading nums1[i] would fail. So the comparison first checks that i is 0 or more; if not, the next value of nums2 goes in. Example 2 starts this way: with m = 0, i is -1 from the beginning.

Java Solution

The method merge works in these steps:

  1. First, set i to m - 1, the last real value of nums1, and j to n - 1, the last value of nums2.
  2. Fill the slots with a for loop: k starts at the last slot, m + n - 1, moves one place left each pass, and the loop runs while j is 0 or more.
  3. In each pass, if i is 0 or more and nums1[i] is larger than nums2[j], copy nums1[i] to slot k and move i left. Otherwise copy nums2[j] there and move j left, which is also what happens when the two values are equal.
  4. When the loop ends, nums1 holds the merged values, so the method has nothing to return.

The main method runs both examples, then a nums1 whose values are all larger than those of nums2, an empty nums2, and arrays with negative numbers and real zeros.

Java
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:

Output
[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] is Example 1, the same result as the last row of the picture. [1] is Example 2: i starts at -1, so the 1 of nums2 goes straight into slot 0.

Look at the third line, [1, 2, 3, 4, 5, 6], merged from [4, 5, 6] and [1, 2, 3]. Here nums1 runs out first: 6, 5 and 4 move to the back in the first three passes, and then 3, 2 and 1 fill the front. A loop that runs only while both i and j are 0 or more stops after those three passes. We ran that version on the same input, and it printed [4, 5, 6, 4, 5, 6]: the 1, 2 and 3 were never copied.

The fourth line, [1, 2, 3], is the empty nums2: j starts at -1, so the loop never runs. In the last line, m = 4 says the zeros at positions 1 and 2 are real values and only the last three are free slots. The result keeps all three zeros, two from nums1 and one from nums2, between -3 and 7.

The original implementation, MergeSortedArray.java, is on GitHub.

Complexity

Each pass of the loop writes one slot of nums1, and the merge keeps nothing but three markers.

  • Time: O(m + n). k moves one slot left per pass and starts at the last of the m + n slots, so there are at most m + n passes.
  • Space: O(1). The values move inside nums1 itself, and the only extra storage is the three markers i, j and k.

The same comparison of two sorted runs is the merge step of merge sort.