Sorted Array

Merge Sorted Array

Easy
Solve it on LeetCode ↗

The problem

Merge sorted array nums2 (n elements) into sorted nums1, which has exactly n trailing empty slots. Do it in place.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Three pointers: i = m − 1 (last real value of nums1), j = n − 1 (last of nums2), k = m + n − 1 (last slot).
  2. 2While j ≥ 0: place the larger of nums1[i] / nums2[j] at position k and step that pointer and k down.
  3. 3When j < 0, remaining nums1 values are already in place — done.

Key insight

Writing into the empty tail means the write pointer can never catch up to the unread values — the in-place hazard disappears by choosing the right direction.

The solution

Watch out for

  • Loop on j (nums2 exhausted), not i — leftover nums1 values need no moves.
  • The i >= 0 guard inside the comparison handles nums1 running out first.