#88

Merge Sorted Array

Easy Merge from the back

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

nums1 has m sorted values followed by n empty slots; nums2 has n sorted values. Merge nums2 into nums1 so the result is sorted, in place.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: merge two sorted arrays into the first one, which has empty space at the end.

Why this works: filling from the front would overwrite numbers we still need. The back is empty, so place the largest numbers there first.

Example: nums1 = [1, 2, 3, 0, 0, 0], nums2 = [2, 5, 6]

compare 3 vs 6 → put 6 at end3 vs 5 → put 53 vs 2 → put 32 vs 2 → put 2 (from nums2)result [1, 2, 2, 3, 5, 6]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Stopping when i runs out — leftover nums2 values still need copying.