Given sorted arrays nums1 (with m real elements + n zeros) and nums2 (n elements), merge them in-place into nums1 in non-decreasing order.
nums1=[1,2,3,0,0,0] m=3, nums2=[2,5,6] n=3[1,2,2,3,5,6]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.
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.
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.
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.