Merge Sorted Array

Pattern: Two pointers

easy

Merge a sorted array into another that has free space at its end, filling from the back so nothing is overwritten.

The problem

You are given two sorted arrays. nums1 has length m + n: its first m values are real and the last n slots are spare (shown as 0). nums2 has n values. Merge nums2 into nums1 so that nums1 holds all m + n values in sorted order. For example, [1, 2, 3, 0, 0, 0] with m = 3 and [2, 5, 6] becomes [1, 2, 2, 3, 5, 6].

The function name merge matches LeetCode, where it changes nums1 and returns nothing. Use the link above for the exact statement.

Think first

  • If you merge from the front, what happens to nums1's own values when you write a smaller value from nums2 into slot 0?
  • Where is the free space in nums1?
  • Which value belongs in the very last slot?

Hints

    Brute force, and why it fails

    Copy nums2 into the spare slots and sort nums1: O((m + n) log(m + n)). Merging into a new array and copying back is O(m + n) but uses extra memory. Filling from the back does it in place in O(m + n).

    The key insight

    The empty space is at the end, and the largest values belong at the end. Merging from the back, largest first, only ever writes into slots that are free or already used up.

    Dry run

    10 
    21 
    32i
    03 
    04 
    05write
    j2 (value 6)

    nums1 = [1, 2, 3, 0, 0, 0] with m = 3 real values, and nums2 = [2, 5, 6]. i and j point at the last real values, and write at the last slot.

    Step 1 of 5

    The plan

    i = m - 1
    j = n - 1
    write = m + n - 1
    while j >= 0:
        if i >= 0 and nums1[i] > nums2[j]:
            nums1[write] = nums1[i];  i = i - 1
        else:
            nums1[write] = nums2[j];  j = j - 1
        write = write - 1
    

    Complexity

    Time
    O(m + n)
    Space
    O(1)

    Each value is written once, and only three indexes are stored.

    Edge cases

    • n = 0: nothing to merge, and the loop does not run.
    • m = 0: every value comes from nums2.
    • All of nums2 smaller than nums1, as in [4, 5, 6] and [1, 2, 3]: nums1's values move to the back first.
    I've built my logic, show the code

    Java

    class Solution {
        public 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
            int write = m + n - 1;                  // fill from the back, where the free space is
            while (j >= 0) {
                if (i >= 0 && nums1[i] > nums2[j]) {
                    nums1[write--] = nums1[i--];
                } else {
                    nums1[write--] = nums2[j--];
                }
            }
        }
    }

    C++

    class Solution {
    public:
        void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
            int i = m - 1;                          // last real value of nums1
            int j = n - 1;                          // last value of nums2
            int write = m + n - 1;                  // fill from the back, where the free space is
            while (j >= 0) {
                if (i >= 0 && nums1[i] > nums2[j]) {
                    nums1[write--] = nums1[i--];
                } else {
                    nums1[write--] = nums2[j--];
                }
            }
        }
    };

    Python

    class Solution:
        def merge(self, nums1: list[int], m: int, nums2: list[int], n: int) -> None:
            i, j = m - 1, n - 1                     # last real value of each
            write = m + n - 1                       # fill from the back, where the free space is
            while j >= 0:
                if i >= 0 and nums1[i] > nums2[j]:
                    nums1[write] = nums1[i]
                    i -= 1
                else:
                    nums1[write] = nums2[j]
                    j -= 1
                write -= 1

    Common mistakes

    • Merging from the front, which overwrites unmerged values.
    • Looping while i >= 0 instead of while j >= 0, which can leave values of nums2 unmerged.
    • Forgetting the i >= 0 check, which reads nums1[-1].

    Similar problems