You are given two integer arrays nums1
and nums2
, sorted in non-decreasing order, and two integers m
and n
, representing the number of elements in nums1
and nums2
respectively.
Merge nums2
into nums1
such that the merged array is also sorted in non-decreasing order.
nums2
into nums1
?
nums1
will have enough space allocated at the end to hold all elements of nums2
.nums1
and nums2
are sorted in non-decreasing order.nums1
has enough space to hold the combined elements of both arrays?
nums1
has a size of m + n
where the last n
elements are empty (0) and can be used to merge nums2
.To merge nums2
into nums1
, we can take a backwards approach. Because both arrays are sorted, we start comparing elements from the end of both arrays and place the larger element at the end of nums1
. This ensures we don’t overwrite any elements in nums1
that we haven’t processed yet:
p1
pointing to the last element of the first m
elements in nums1
p2
pointing to the last element in nums2
p
pointing to the last position of nums1
nums1[p1]
and nums2[p2]
nums1[p]
p
backwardp1
or p2
) backwardnums2
(i.e., p2
>= 0), copy them into nums1
.Here is the Python implementation of the strategy described:
def merge(nums1, m, nums2, n):
# Start from the last positions of nums1 and nums2 respectively
p1 = m - 1
p2 = n - 1
p = m + n - 1
# Merge in reverse order
while p1 >= 0 and p2 >= 0:
if nums1[p1] > nums2[p2]:
nums1[p] = nums1[p1]
p1 -= 1
else:
nums1[p] = nums2[p2]
p2 -= 1
p -= 1
# If there are remaining elements in nums2, copy them
# This caters for cases where all elements in nums1 are already in correct position
while p2 >= 0:
nums1[p] = nums2[p2]
p -= 1
p2 -= 1
nums1
and nums2
exactly once.nums1
in place.This method solves the problem efficiently and adheres to the constraints provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?