Merge Sorted Array
LeetCode 88 · Easy · solution, intuition & step-by-step walkthrough
Three pointers, filling nums1 from the end.
This is how I solved Merge Sorted Array (LeetCode 88), an easy problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
nums1 has empty space at the end, so fill it from the back. Compare the largest remaining element of each array and drop the larger one into the last free slot; nothing you still need is ever overwritten.
Approach
- 1
r1 = m−1, r2 = n−1, k = m+n−1.
- 2
While both have elements, move the larger to nums1[k].
- 3
Copy any leftovers from nums2 (leftovers in nums1 are already in place).
How I solved it
Three pointers from the endPythonO(m+n) time · O(1) space
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
k = m+n-1
r1=m-1
r2=n-1
while r1>=0 and r2>=0:
if nums1[r1]>nums2[r2]:
nums1[k]=nums1[r1]
r1-=1
else:
nums1[k]=nums2[r2]
r2-=1
k-=1
while r1>=0:
nums1[k]=nums1[r1]
r1-=1
k-=1
while r2>=0:
nums1[k]=nums2[r2]
r2-=1
k-=1
Merge Sorted Array — FAQ
What is the intuition behind Merge Sorted Array?
nums1 has empty space at the end, so fill it from the back. Compare the largest remaining element of each array and drop the larger one into the last free slot; nothing you still need is ever overwritten.
How do you solve Merge Sorted Array (LeetCode 88)?
1. r1 = m−1, r2 = n−1, k = m+n−1. 2. While both have elements, move the larger to nums1[k]. 3. Copy any leftovers from nums2 (leftovers in nums1 are already in place).
What is the time and space complexity of Merge Sorted Array?
Time: O(m + n). Space: O(1). (Accepted approach: Three pointers from the end.)
What are common mistakes in Merge Sorted Array?
Filling from the front would overwrite elements of nums1 you haven't placed yet.