Algo-Sim › Two Pointers

Merge Sorted Array

Easy · Two Pointers · step through it in Java, Python and C++ on your own input

Merge nums2 into the spare tail of nums1 by filling from the back, so nothing unread is overwritten.

Problem

Two arrays nums1 and nums2 are sorted in non-decreasing order and hold m and n values. nums1 has length m + n: its last n slots are spare zeros. Merge nums2 into nums1 in place so that nums1 ends up sorted.

Constraints

Edge cases to test

Follow-up questions

Why fill from the back?
The spare space is at the end of nums1, so writing the largest values there never overwrites an unread value: O(m + n), O(1) extra.
What if you must merge k sorted arrays?
A min-heap of the k current heads: O(N log k) for N values in total.

Solution

Java

public 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--];
        }
    }
}

Python

def merge(nums1, m, nums2, n):
    i, j, w = m - 1, n - 1, m + n - 1
    while j >= 0:
        if i >= 0 and nums1[i] > nums2[j]:
            nums1[w] = nums1[i]
            i, w = i - 1, w - 1
        else:
            nums1[w] = nums2[j]
            j, w = j - 1, w - 1

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    void merge(vector<int> &nums1, int m, vector<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--];
            }
        }
    }
};

More Two Pointers problems