Merge Sorted Array

EasyTwo Pointers · Merge from the Back🧩 Two PointersLeetCode #88 ↗Updated

Problem

Two arrays are sorted in non-decreasing order: nums1 holds m real values followed by n placeholder zeros, and nums2 holds n values. Merge nums2 into nums1 in-place so that all m + n slots end up sorted. Nothing is returned.
Inputnums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3Output[1,2,2,3,5,6]
Inputnums1 = [1], m = 1, nums2 = [], n = 0Output[1]
Inputnums1 = [0], m = 0, nums2 = [1], n = 1Output[1]

0 ≤ m, n ≤ 200  ·  1 ≤ m + n  ·  -109 ≤ values ≤ 109  ·  Follow-up: O(m + n) time.

Try it yourself

Java
class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The free space sits at the end of nums1. Fill it from the back with the larger of the two current tails — the write pointer can never overtake an unread value of nums1.
PatternTwo Pointers

Instinct Sorted input, a pair/triple hitting a target, or something symmetric? Put one pointer at each end and move the one that can only improve things.

Memory hack Squeeze from both ends - every step throws away a whole row of the brute-force grid.

Open the Two Pointers guide →

Approaches

Brute ForceAppend, then Sort

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

Copy nums2 into the placeholder slots and sort the whole array. Correct because the final content is just the union of both arrays in order; the space is the sort's recursion stack.

Java
public void merge(int[] nums1, int m, int[] nums2, int n) {
    for (int i = 0; i < n; i++) {
        nums1[m + i] = nums2[i];
    }
    Arrays.sort(nums1);
}

Two lines, but ignores that both halves are already sorted.

At a glance

LevelApproachTimeSpace
Brute ForceAppend, then SortO((m+n) log(m+n))O(log(m+n))
BetterCopy Prefix, Merge ForwardO(m + n)O(m)
OptimalThree Pointers from the EndO(m + n)O(1)
Common pitfalls
  • Merging front-to-back in place — overwrites nums1 values before reading them.
  • Forgetting the i >= 0 guard when m = 0 (index -1).
  • Returning a new array — the result must live in nums1.
Interview tips
  • Point out where the free space is: that is the hint to merge backwards.
  • Explain why w never passes i (w - i = j + 1 > 0).
  • Mention that leftover nums1 elements need no copying.
Pattern
Reverse two-pointer merge → merge sorted data in-place when the spare room is at the end of the destination.
My notes saved in this browser