Merge Sorted Array (LeetCode 88): Solution and Explanation

Easy
Array
Two Pointers
Sorting

You have two sorted integer arrays. The first, nums1, has room for m + n values, but only its first m slots hold real data and the rest are placeholders. Merge the n values of nums2 into nums1 so that nums1 ends up fully sorted, modifying it in place instead of returning a new array.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The lazy solution copies nums2 into the empty tail of nums1 and sorts the whole thing. That is correct and short, but it costs O((m + n) log(m + n)) and ignores the fact that both inputs are already sorted. The textbook merge from merge sort is linear, so the real question is how to do that merge without a separate output array.

If you merge from the front, you hit a problem immediately: writing the smallest value into nums1[0] overwrites a real element of nums1 that you have not placed yet. You would need to shift elements or copy nums1 aside first, which costs extra time or memory.

The trick is to merge from the back. The free space in nums1 sits at the end, and the largest values belong at the end. So compare the largest unplaced element of each array, write the bigger one into the last free slot, and move left. The write pointer always stays at or to the right of the nums1 read pointer, so you never overwrite something you still need. When nums2 runs out, whatever remains of nums1 is already in the correct place, and the loop can stop.

Approach: Three pointers from the end

  1. Set p1 = m - 1 for the last real element of nums1, p2 = n - 1 for the last element of nums2, and p = m + n - 1 for the last slot.
  2. Loop while p2 >= 0, since the merge is finished once every value from nums2 is placed.
  3. If p1 is still valid and nums1[p1] > nums2[p2], write nums1[p1] into nums1[p] and decrement p1.
  4. Otherwise write nums2[p2] into nums1[p] and decrement p2. This branch also covers the case where nums1 is exhausted.
  5. Decrement p after each write. When the loop ends, the leftover prefix of nums1 is already sorted and in place.

Step-by-step example

nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
  1. Start with p1 = 2, p2 = 2 and p = 5. Compare 3 with 6: 6 is larger, so nums1[5] = 6 and p2 becomes 1.
  2. Compare 3 with 5: nums1[4] = 5 and p2 becomes 0.
  3. Compare 3 with 2: 3 is larger, so nums1[3] = 3 and p1 becomes 1.
  4. Compare 2 with 2: they are equal, so the else branch writes the 2 from nums2 into nums1[2] and p2 becomes -1.
  5. The loop stops. nums1 is [1, 2, 2, 3, 5, 6], and the first two values never had to move.

Code: Python, Java, C++

1class Solution:
2    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
3        p1, p2, p = m - 1, n - 1, m + n - 1
4
5        while p2 >= 0:
6            if p1 >= 0 and nums1[p1] > nums2[p2]:
7                nums1[p] = nums1[p1]
8                p1 -= 1
9            else:
10                nums1[p] = nums2[p2]
11                p2 -= 1
12            p -= 1

Time and space complexity

Time

O(m + n)

Each iteration places exactly one element and moves one of the read pointers left, and the loop ends after at most m + n placements.

Space

O(1)

The merge happens inside nums1 using three integer pointers, with no extra array.

Other approaches

Copy and sort (time O((m + n) log(m + n)), space O(log(m + n)) to O(m + n) depending on the sort)

Copy nums2 into the tail of nums1 and call a built-in sort. It is a one-liner and fine for tiny inputs, but it throws away the sortedness of the inputs.

Forward merge with a copy (time O(m + n), space O(m))

Copy the first m values of nums1 into a temporary array, then do the standard front-to-back merge into nums1. It is linear and easy to explain, but uses O(m) extra memory.

Common mistakes

  • Looping while p1 >= 0 instead of p2 >= 0. If nums1 runs out first, the remaining nums2 values would never be copied.
  • Forgetting to check p1 >= 0 before reading nums1[p1]. In Python a negative index silently reads from the end of the array and produces a wrong merge.
  • Merging from the front without a buffer, which overwrites values of nums1 that have not been placed yet.
  • Returning a new list. The function is expected to modify nums1 in place, and the caller checks that array.

Frequently asked questions

Why merge from the end in Merge Sorted Array?

The empty space is at the end of nums1, so filling from the back writes only into slots that are free or already consumed. Merging from the front would overwrite unread values of nums1.

Why does the loop only check p2?

Once every value from nums2 has been placed, the remaining elements of nums1 are already sorted and sitting in their final positions, so there is nothing left to do.

What is the time complexity of Merge Sorted Array?

It is O(m + n), because each step places one element and there are m + n elements in total. The space complexity is O(1).

What if nums1 is empty except for buffer space?

When m is 0, p1 starts at -1, so every iteration takes the else branch and copies nums2 into nums1 in order. The code handles it without a special case.