Taro Logo

Merge Sorted Array

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+28
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2.1K views
Topics:
ArraysTwo Pointers

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 + n
  • nums2.length == n
  • 0 <= m, n <= 200
  • 1 <= m + n <= 200
  • -109 <= nums1[i], nums2[j] <= 109

Follow up: Can you come up with an algorithm that runs in O(m + n) time?

Solution


Clarifying Questions

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:

  1. Can the arrays contain negative numbers, or are we guaranteed that all elements are non-negative integers?
  2. How are the element counts ($m$ and $n$) defined relative to the physical size of the first array, and is the extra space in `nums1` guaranteed to be initialized to zeros or some placeholder?
  3. How should we handle cases where one or both of the arrays are completely empty ($m = 0$ or $n = 0$)?
  4. If there are duplicate values across the two arrays, are they all preserved, and does the merge need to maintain a specific stability order for duplicates?
  5. Since the problem description mentions returning the modified first array, should my function also explicitly return the reference to `nums1` for chaining, or is a `void` return type expected?

Brute Force Solution

Approach

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:

  1. Take all the items from the first pile and place them into a brand new empty container.
  2. Take all the items from the second pile and dump them into that same new container right alongside the first set.
  3. Look at everything currently sitting in the new container in a completely jumbled order.
  4. Carefully rearrange the entire collection by comparing every item against every other item until they are all lined up in perfect numerical order from smallest to largest.
  5. Present this newly sorted collection as your final combined result.

Code Implementation

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()

Big(O) Analysis

Time Complexity
O((m + n) log(m + n)) – Combining the two piles into a single container of size m plus n takes linear time, where we copy all elements. Afterward, sorting this entire combined collection from scratch requires a comparison-based sort, which dominates the runtime. This results in roughly (m + n) * log(m + n) operations, which simplifies to the final Big O time complexity.
Space Complexity
O(1) – The brute force approach described involves creating a brand new empty container to hold all combined items before sorting them from scratch. This brand new container requires an auxiliary array whose size scales directly with the total number of elements from both input piles, effectively requiring extra memory proportional to the combined input size. Consequently, if we define N as the total number of elements across both input piles, the algorithm utilizes an auxiliary data structure of size N to store the intermediate results. Simplifying this extra memory requirement to Big O notation yields a space complexity of O(N).

Optimal Solution

Approach

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:

  1. Look at the end of the main space where the final sorted items are supposed to land.
  2. Find the biggest item currently sitting at the back of the first group and compare it with the biggest item sitting at the back of the second group.
  3. Take the larger of these two items and place it into the very last available slot at the back of the main space.
  4. Shift your attention one spot forward in whichever group just gave away its item.
  5. Repeat this comparison and placement process, always working backward from the end toward the front.
  6. Continue this backward journey until all items from the second group have successfully found their proper places in the main space.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(m + n) – The cost is driven by a single backward traversal that visits every element in both input groups exactly once. We compare the tail elements of both arrays and place the larger one into the end of the main space, decrementing our pointers step by step. This process performs roughly (m + n) constant-time comparison and assignment operations. Therefore, the total operations scale linearly with the combined input size, simplifying to O(m + n).
Space Complexity
O(1) – The algorithm performs all merging operations directly in place within the pre-allocated space of the main array. It relies exclusively on a few primitive pointer variables to track indices at the ends of the groups rather than allocating any auxiliary data structures. Consequently, the extra memory usage remains entirely constant regardless of the total number of elements N. Thus, the auxiliary space complexity simplifies to Big O of 1.

Edge Cases

The second array is completely empty
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Standard numerical comparisons treat negatives as smaller than zeros and positives, which works identically during backward merging.
Arrays containing heavy duplicates and identical values
How to Handle:
Conditional checks ensuring stable relative ordering handle duplicates correctly without breaking sort properties.
Maximum possible constraint sizes for both arrays
How to Handle:
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
How to Handle:
Pointers initialize at the last valid index and compare the single values to place the larger one at the very end.
0/75 completed