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 nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0 Output: [1] Explanation: The arrays we are merging are [1] and []. The result of the merge is [1].
Example 3:
Input: nums1 = [0], m = 0, nums2 = [1], n = 1 Output: [1] Explanation: The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
Constraints:
nums1.length == m + nnums2.length == n0 <= m, n <= 2001 <= m + n <= 200-109 <= nums1[i], nums2[j] <= 109Follow up: Can you come up with an algorithm that runs in O(m + n) time?
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have two separate piles of sorted items and you want to combine them into one single pile. The brute force approach simply involves throwing all the items together into a brand new pile and then sorting the whole thing from scratch.
Here's how the algorithm would work step-by-step:
def merge(first_array, first_length, second_array, second_length):
# Combine all elements into the first array container to pool the inputs together
for insertion_index in range(second_length):
first_array[first_length + insertion_index] = second_array[insertion_index]
# Sort the entire collection from scratch to establish proper numerical order
first_array.sort()Instead of starting from the beginning and messing up already sorted items, the optimal strategy starts from the very end where the biggest items belong. By comparing the largest available pieces from both groups and placing the winner at the very back, we can quietly fill everything in place without disturbing the rest.
Here's how the algorithm would work step-by-step:
def merge(primary_array, first_element_count, secondary_array, second_element_count):
pointer_first = first_element_count - 1
pointer_secondary = second_element_count - 1
target_pointer = first_element_count + second_element_count - 1
# Working backwards prevents overwriting unprocessed elements in the primary array.
while pointer_first >= 0 and pointer_secondary >= 0:
if primary_array[pointer_first] > secondary_array[pointer_secondary]:
primary_array[target_pointer] = primary_array[pointer_first]
pointer_first -= 1
else:
primary_array[target_pointer] = secondary_array[pointer_secondary]
pointer_secondary -= 1
target_pointer -= 1
# Remaining elements in the secondary array are already smaller than everything left.
while pointer_secondary >= 0:
primary_array[target_pointer] = secondary_array[pointer_secondary]
pointer_secondary -= 1
target_pointer -= 1| Case | How to Handle |
|---|---|
| The second array is completely empty | The algorithm naturally completes instantly since the pointer for the second array starts below zero and no copying occurs. |
| The first array has zero initial elements while the second array contains all elements | The backward pointer placement correctly copies all elements from the second array directly into the front of the first array. |
| All elements in the second array are smaller than all elements in the first array | The backward traversal compares and shifts all original elements of the first array to the end before placing the second array elements. |
| All elements in the second array are larger than all elements in the first array | The second array elements are exhausted and placed into the final positions of the first array while leaving the original first array intact. |
| Arrays containing negative numbers, zeros, and mixed positive values | Standard numerical comparisons treat negatives as smaller than zeros and positives, which works identically during backward merging. |
| Arrays containing heavy duplicates and identical values | Conditional checks ensuring stable relative ordering handle duplicates correctly without breaking sort properties. |
| Maximum possible constraint sizes for both arrays | An in place linear time approach operating in O m plus n time and O 1 auxiliary space efficiently avoids memory limits. |
| Both arrays containing single elements | Pointers initialize at the last valid index and compare the single values to place the larger one at the very end. |