Problem Statement
Merge Sorted Array
You get two lists of numbers, nums1 and nums2. Both are already sorted from smallest to largest. You also get two counts: m is how many real numbers live in nums1, and n is how many real numbers live in nums2. Your job is to fold all of nums2 into nums1 so that nums1 ends up as one big sorted list. The trick is that nums1 is already the right size to hold everything. It has m real numbers at the front and n empty slots (filled with zeros) at the back, waiting to be used.
Signals to notice
Brute force first
Copy both into new array and merge. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.
The key insight
Fill from the end using three pointers. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.
Trace it on nums1=[1,2,3,0,0,0], m=3, nums2=[2,5,6], n=3
init: p1=2 (val 3), p2=2 (val 6), p=5 3>6? no -> nums1[5]=6; p2=1, p=4; nums1=[1,2,3,0,0,6] 3>5? no -> nums1[4]=5; p2=0, p=3; nums1=[1,2,3,0,5,6] 3>2? yes -> nums1[3]=3; p1=1, p=2; nums1=[1,2,3,3,5,6] 2>2? no -> nums1[2]=2; p2=-1, p=1; nums1=[1,2,2,3,5,6] p2<0: main loop ends; tail loop skipped (p2<0) return nums1=[1,2,2,3,5,6]
What must stay true
Fill from the back to avoid overwriting elements in nums1 that haven't been processed. As long as that statement keeps holding, you can trust the steps built on top of it.
Shape of the loop
p1, p2, p = m-1, n-1, m+n-1
while p1 >= 0 and p2 >= 0:
if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1]; p1 -= 1
else: nums1[p] = nums2[p2]; p2 -= 1
p -= 1
while p2 >= 0: nums1[p] = nums2[p2]; p2 -= 1; p -= 1Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Filling from the front — you'd overwrite elements in nums1 you still need. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.