Merge Sorted Array (LeetCode 88): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Set
p1 = m - 1for the last real element ofnums1,p2 = n - 1for the last element ofnums2, andp = m + n - 1for the last slot. - Loop while
p2 >= 0, since the merge is finished once every value fromnums2is placed. - If
p1is still valid andnums1[p1] > nums2[p2], writenums1[p1]intonums1[p]and decrementp1. - Otherwise write
nums2[p2]intonums1[p]and decrementp2. This branch also covers the case wherenums1is exhausted. - Decrement
pafter each write. When the loop ends, the leftover prefix ofnums1is already sorted and in place.
Step-by-step example
nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
- Start with
p1 = 2,p2 = 2andp = 5. Compare 3 with 6: 6 is larger, sonums1[5] = 6andp2becomes 1. - Compare 3 with 5:
nums1[4] = 5andp2becomes 0. - Compare 3 with 2: 3 is larger, so
nums1[3] = 3andp1becomes 1. - Compare 2 with 2: they are equal, so the else branch writes the 2 from
nums2intonums1[2]andp2becomes -1. - The loop stops.
nums1is [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 -= 11class Solution {
2 public void merge(int[] nums1, int m, int[] nums2, int n) {
3 int p1 = m - 1, p2 = n - 1, p = m + n - 1;
4
5 while (p2 >= 0) {
6 if (p1 >= 0 && nums1[p1] > nums2[p2]) {
7 nums1[p] = nums1[p1];
8 p1--;
9 } else {
10 nums1[p] = nums2[p2];
11 p2--;
12 }
13 p--;
14 }
15 }
16}1class Solution {
2public:
3 void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
4 int p1 = m - 1, p2 = n - 1, p = m + n - 1;
5
6 while (p2 >= 0) {
7 if (p1 >= 0 && nums1[p1] > nums2[p2]) {
8 nums1[p] = nums1[p1];
9 p1--;
10 } else {
11 nums1[p] = nums2[p2];
12 p2--;
13 }
14 p--;
15 }
16 }
17};Time and space complexity
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.
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 >= 0instead ofp2 >= 0. Ifnums1runs out first, the remainingnums2values would never be copied. - Forgetting to check
p1 >= 0before readingnums1[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
nums1that have not been placed yet. - Returning a new list. The function is expected to modify
nums1in 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.