Fill nums1 from the right
The tail of nums1 is empty. Write the larger of the two remaining heads into the next empty slot, working right-to-left so you never overwrite an unread value.
Merging left-to-right would clobber unread values in nums1. The empty suffix is free space — use it.
Algorithm
- i = m−1, j = n−1, w = m+n−1.
- While both sides remain, write the larger into
nums1[w]and decrement. - Copy any leftover
nums2prefix.
- Time
- O(m + n)
- Space
- O(1)
class Solution: def merge(self, nums1: list[int], m: int, nums2: list[int], n: int) -> list[int]: i, j, w = m - 1, n - 1, m + n - 1 while j >= 0: if i >= 0 and nums1[i] > nums2[j]: nums1[w] = nums1[i] i -= 1 else: nums1[w] = nums2[j] j -= 1 w -= 1 return nums1