← Back to DSA Animator
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.