Easy dsa two-pointers

Merge Sorted Array

The 30 second answer

nums1 has spare room at the end, so I fill it from the back. I compare the last unused values of nums1 and nums2 and write the larger one into the next free slot from the right. That way I never overwrite a value I still need, and leftover nums2 values copy across. Linear time and constant extra space.

Could you say this in an interview?

Problem You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two counts m and n. Merge nums2 into nums1 as one sorted array in place. nums1 has length m + n, with m values at the front and n zeros at the end as buffer. Original: LeetCode 88: Merge Sorted Array.

Understanding the prompt The result must land in nums1. Writing from the front would overwrite values you have not yet compared. The buffer at the end is there so you can write from the back.

Pattern recognition Two read pointers and one write pointer, all moving in the same direction, here from right to left. It is the in-place form of merging two sorted sequences.

Brute force Copy the first m values aside, then merge into nums1 from the left: O(m + n) time but O(m) extra space. Concatenate and sort: O((m + n) log (m + n)).

Optimal Let i be the last live value in nums1, j the last value in nums2, and w the last slot of nums1. While j is still in range, write the larger of nums1[i] and nums2[j] into w and step that read pointer back. If nums1 runs out first, the rest of nums2 copies in. If nums2 runs out first, the remaining prefix of nums1 is already in place.

Alternatives If you were allowed a new array, merge from the front, which is the same idea as Merge Two Sorted Lists.

Java solution

import java.util.Arrays;

public class MergeSortedArray {
    static void merge(int[] nums1, int m, int[] nums2, int n) {
        int i = m - 1, j = n - 1, w = m + n - 1;
        while (j >= 0) {
            if (i >= 0 && nums1[i] > nums2[j]) nums1[w--] = nums1[i--];
            else nums1[w--] = nums2[j--];
        }
    }

    public static void main(String[] args) {
        var a = new int[] {1, 2, 3, 0, 0, 0};
        merge(a, 3, new int[] {2, 5, 6}, 3);
        System.out.println(Arrays.toString(a)); // [1, 2, 2, 3, 5, 6]
        var b = new int[] {1};
        merge(b, 1, new int[] {}, 0);
        System.out.println(Arrays.toString(b)); // [1]
        var c = new int[] {0};
        merge(c, 0, new int[] {1}, 1);
        System.out.println(Arrays.toString(c)); // [1]
    }
}

Complexity O(m + n) time, O(1) extra space.

Edge cases

  • nums2 is empty: nums1 is already the answer.
  • nums1 has no live values (m = 0): copy nums2 across, as in [0] and 1.
  • Duplicates, as in [1,2,3,0,0,0] and [2,5,6].

Follow-ups

  • Merge Two Sorted Lists, the linked-list form of the same merge.
  • Merge k sorted arrays, which needs a heap.

Tests [1,2,3,0,0,0] with m=3 and [2,5,6] with n=3 becomes [1,2,2,3,5,6]. 1 with an empty nums2 stays 1. [0] with m=0 and 1 becomes 1.

How to say it in the interview " nums1 has spare slots at the end, so I merge from the back. I compare the last unused values and write the larger one into the next slot from the right, so I never overwrite something I still need. If nums2 is exhausted, nums1's prefix is already correct. Linear time, constant space."

Sources (1)
  1. LeetCode 88: Merge Sorted Arrayleetcode.com