LeetCode #88 Easy

Merge Sorted Array

Merge Sorted Array is LeetCode 88 (Easy). You get two arrays sorted in non-decreasing order:

  • nums1 has length m + n. Its first m values are real; the last n places are zeros that only reserve space.
  • nums2 holds n values.

Merge nums2 into nums1 so that nums1 becomes one sorted array of m + n values. Nothing is returned; the result must be written in place inside nums1. The follow-up asks for O(m + n) time.

Constraints
  • nums1.length == m + n
  • nums2.length == n
  • 0 <= m, n <= 200
  • 1 <= m + n <= 200
  • -10⁹ <= nums1[i], nums2[j] <= 10⁹
arraytwo-pointers
Open on LeetCode ↗
02

Intuition

To merge two sorted arrays you repeatedly pick the next value from the front of one of them. Doing that from the left here would overwrite nums1 values you have not read yet. The empty space sits at the right end, so fill nums1 from the back with the largest value left.

  • Which value is largest: it is either the last unplaced value of nums1 or the last unplaced value of nums2.
  • Why nothing is lost: while nums2 still has j + 1 values to place, the write slot is exactly j + 1 places right of the last unread nums1 value. The write position can never reach a value you still need.
How to spot this pattern

An in-place merge where the spare room sits at one end of the target array. Fill from the end that has the room, and every write lands on space that is already free.

03

Approach

Try it first

Before reading on, decide which value must end up in the very last slot of nums1, and where it can come from. Then check what happens when one array runs out first. Aim for O(m + n) time and no extra array.

1

Point at the three right ends

Set i = m - 1 (last real value of nums1), j = n - 1 (last value of nums2) and k = m + n - 1 (last slot). The largest unplaced value always belongs in slot k.

2

Move the larger value to slot k

If i >= 0 and nums1[i] > nums2[j], copy nums1[i] into slot k and move i left. Otherwise copy nums2[j] and move j left. Then move k left, because that slot is now final.

3

Stop when nums2 is used up

Loop while j >= 0. Once every nums2 value is placed, the nums1 values still unmoved are its smallest ones, already sorted and already in slots 0 to i, so no more work is needed.

4

Why the write never overwrites

Each step places one value, so k - i always equals the number of nums2 values still waiting, j + 1. That count is at least 1 inside the loop, so slot k is always to the right of every unread nums1 value.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def merge(self, nums1, m, nums2, n):
▶3 i, j, k = m - 1, n - 1, m + n - 1
▶4 while j >= 0:
▶5 if i >= 0 and nums1[i] > nums2[j]:
▶6 nums1[k] = nums1[i]
▶7 i -= 1
▶8 else:
▶9 nums1[k] = nums2[j]
▶10 j -= 1
▶11 k -= 1
nums1nums2123256ikjstart at the right end: slot 5
i2last unplaced in nums1
j2last unplaced in nums2
k53 slots from i
i points at the largest real value in nums1, j at the largest in nums2, and k at the last slot. The biggest value of all belongs in slot 5, and it must be either nums1[i] or nums2[j].
nums1nums21236256ikj6 beats 3 → copy 6 to slot 5
i2last unplaced in nums1
j2last unplaced in nums2
k53 slots from i
nums2 holds the larger value, 6 against 3, so it goes to slot 5. Slot 5 is still 3 places right of i, so no unread nums1 value is overwritten.
nums1nums212356256ikj5 beats 3 → copy 5 to slot 4
i2last unplaced in nums1
j1last unplaced in nums2
k42 slots from i
nums2 holds the larger value, 5 against 3, so it goes to slot 4. Slot 4 is still 2 places right of i, so no unread nums1 value is overwritten.
nums1nums2123356256ikj3 beats 2 → move 3 to slot 3
i2last unplaced in nums1
j0last unplaced in nums2
k31 slot from i
nums1 holds the larger value, 3 against 2, so 3 is the largest left and goes to slot 3. Its old slot becomes free space for later writes.
nums1nums2122356256ikjtie at 2 → copy 2 to slot 2
i1last unplaced in nums1
j0last unplaced in nums2
k21 slot from i
Both values are 2. The test asks whether nums1's value is strictly larger, so the tie goes to nums2; either choice gives the same array.
nums1nums2122356256nums2 used up → nums1 is sorted
nums1[1, 2, 2, 3, 5, 6]merged
j fell below 0, so the loop stops. The values left in nums1 at slots 0 to 1 were never moved, and they are already in the right place.
05

Common pitfalls

Merging from the front

✗ Wrong
i = j = k = 0
# write the smaller of nums1[i], nums2[j] to nums1[k]
✓ Right
i, j, k = m - 1, n - 1, m + n - 1
# write the larger to nums1[k], moving left

With nums1 = [1, 2, 3, 0, 0, 0] and nums2 = [2, 5, 6], the third write puts nums2's 2 into slot 2 and destroys the 3 before it is read. The front of nums1 is full; only the back is free.

Looping only while both arrays have values

✗ Wrong
while i >= 0 and j >= 0:
✓ Right
while j >= 0:

With nums1 = [4, 5, 6, 0, 0, 0] and nums2 = [1, 2, 3], nums1 runs out after three moves and the loop stops, leaving [4, 5, 6, 4, 5, 6]. The values 1, 2 and 3 are never copied.

Dropping the i >= 0 check

✗ Wrong
if nums1[i] > nums2[j]:
✓ Right
if i >= 0 and nums1[i] > nums2[j]:

With nums1 = [2, 0], m = 1 and nums2 = [1], i becomes -1 after the 2 moves right. Python then reads nums1[-1], the 2 just written, copies it again and soon raises an IndexError; C++ and Java read outside the array.

06

Edge cases

n = 0

j starts at -1, so the loop never runs and nums1 stays as it is.

m = 0

i starts at -1, so every step takes the nums2 branch and copies nums2 into nums1 in order.

07

Complexity

Time
O(m + n)
Space
O(1)
Each slot of nums1 is written at most once, and only three index variables are used.
08

Merge Sorted Array FAQ

Why not copy nums2 into the empty slots and sort?

It works and is short, but sorting costs O((m + n) log(m + n)). It ignores the fact that both inputs are already sorted, which is what makes the linear merge possible.

What if nums1 has no empty slots at the end?

That is a different problem, often called merging without extra space: the smallest values must end up in the first array and the rest in the second. Filling from the back no longer works, and the usual answers are the gap method or swapping across the two arrays and re-sorting.