DSA AnimatorDSA animations
Merge Sorted Array LC #88 Easy Two Pointers · Merge
Problem

Given sorted arrays nums1 (with m real elements + n zeros) and nums2 (n elements), merge them in-place into nums1 in non-decreasing order.

Example 1
Input: nums1=[1,2,3,0,0,0] m=3, nums2=[2,5,6] n=3
Output: [1,2,2,3,5,6]
Constraints: m,n≥0  |  nums1.length==m+n  |  −10⁹≤nums[i]≤10⁹
Try Examples
Custom:
Approach
Three Pointers — Fill from the Back
p1 starts at nums1[m-1], p2 at nums2[n-1], p (write) at m+n-1. Compare p1 and p2 values; write the larger one at position p. Move pointers left. Never overwrites unread values!
Arrays
Variables
p1 (nums1)
—
p2 (nums2)
—
p (write)
—
written
—
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Set p1=m-1, p2=n-1, p=m+n-1 (write from end)
2
While p1≥0 and p2≥0: compare nums1[p1] vs nums2[p2]
3
Write the larger value at nums1[p], advance that pointer left
4
Copy remaining nums2 elements (if any)
Time
O(m+n)
Space
O(1)
Why Merge from the Back?

Merging from the front would overwrite unseen nums1 elements. By starting at the end of nums1 (where the zeros are), we fill the largest slot first. The write pointer p always lands in the "used-up" region — we can never clobber an unread value.

How to solve Merge Sorted Array

LeetCode 88 · Easy · Arrays · Pattern: Two Pointers

Why the obvious approach is slow

Copying nums 2 into the empty slots and sorting costs O(n log n). Merging from the front would overwrite values in nums 1 before you have used them.

The key idea

Merge from the back instead, where the empty space is. Compare the largest remaining value of each array, and write the bigger one into the last free slot. Nothing gets overwritten, because the write position is always behind the values still to be read.

Remember

When there is free space at the end, merge from the back. Stop when the second array is empty; anything left in the first is already in place.

Run the animation above on your own input, or watch the 1:43 video explanation of Merge Sorted Array with a dry run and Java code.

More Arrays problems