Merge Sorted Array

Updated on 12 June, 2025
Merge Sorted Array header image

Problem Statement

In this task, we are provided with two sorted integer arrays, nums1 and nums2. We are also given two integers, m and n, indicating the number of active elements in nums1 and nums2, respectively. The goal is to merge nums1 and nums2 into a single sorted array in non-decreasing order. The merged result should not be returned but stored within nums1. To facilitate the merging, the array nums1 is structured to have a length of m + n, where the first m entries are the initial elements, and the remaining n slots are initially zeroed out to accommodate the elements of nums2. It is crucial to ensure the elements from both arrays are merged directly into nums1 without using additional arrays for output.

Examples

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

Approach and Intuition

Before diving into the solution, understanding the constraints and the default setup of nums1 and nums2 is essential. Here's a structured approach to achieve the merging:

  1. Utilize two pointers starting from the end of the active elements of both arrays (m-1 for nums1 and n-1 for nums2). Additionally, use a third pointer to place elements from the end to the beginning of nums1, starting at the position m+n-1.
  2. Compare the elements at these pointers:
    • If the element in nums2 is greater than or equal to the element in nums1, place the nums2 element at the current index in nums1 determined by the third pointer, and move the pointer in nums2 backwards.
    • Otherwise, move the element in nums1 to the current index, and move the pointer in nums1 backward.
  3. If elements remain in nums2 after nums1 is exhausted, copy them directly to the beginning of nums1.

These steps ensure that we manipulate nums1 in-place, adhering to the memory constraints and the requirement to not return the merged array but store it within nums1. The decision to merge from the back of nums1 allows us to efficiently utilize its space without overwriting any elements before they are merged. This method leverages the sorted property of the arrays, ensuring that at each step, the largest of the remaining elements is correctly placed at the end of nums1, filling up from back to front.

Solutions

  • C++
  • Java
  • JavaScript
  • Python
cpp
class Solution {
public:
    void mergeSortedArrays(vector<int>& first, int size1, vector<int>& second, int size2) {
        int index1 = size1 - 1;
        int index2 = size2 - 1;
        for (int indexMerged = size1 + size2 - 1; indexMerged >= 0; indexMerged--) {
            if (index2 < 0) {
                break;
            }
            if (index1 >= 0 && first[index1] > second[index2]) {
                first[indexMerged] = first[index1--];
            } else {
                first[indexMerged] = second[index2--];
            }
        }
    }
};

The provided C++ code defines a method mergeSortedArrays that merges two presorted integer vectors into one of the vectors, specifically into the first vector. The function takes two vectors, first and second, and their respective sizes, size1 and size2.

  • The code initializes two pointers, index1 and index2, at the end of the non-empty parts of both first and second vectors respectively.
  • A third pointer, indexMerged, is also initialized at the last position of the combined array size.
  • It uses a for loop to iterate backwards through the first vector's extended size (which includes room for the second vector's elements).
  • Inside the loop, the elements from first and second are compared. The larger element is placed into the current position of indexMerged in the first vector.
  • The loop terminates early if all elements from the second vector have been placed into the first.

This method ensures that the merged array is sorted without needing additional storage space, effectively integrating the two arrays into a single sorted array in a space-efficient manner. This solution is particularly efficient for scenarios where extra space utilization needs to be minimized.

java
class Solution {
    public void mergeSortedArrays(int[] array1, int len1, int[] array2, int len2) {
        int index1 = len1 - 1;
        int index2 = len2 - 1;

        for (int i = len1 + len2 - 1; i >= 0; i--) {
            if (index2 < 0) {
                break;
            }
            if (index1 >= 0 && array1[index1] > array2[index2]) {
                array1[i] = array1[index1--];
            } else {
                array1[i] = array2[index2--];
            }
        }
    }
}

The provided Java solution tackles the problem of merging two sorted arrays into one sorted array. The approach modifies the first array (array1) to include all elements from both arrays, as it assumes that array1 has enough space to hold elements from both array1 and array2.

Here's how the merging process is executed:

  • Initialize two pointers, index1 and index2, to point to the ends of array1 and array2 respectively.
  • Use a loop that goes backwards through array1, starting from its last position, which is the sum of len1 and len2 minus one, and decrements down to zero.
  • In each iteration of the loop:
    • If index2 is less than zero, end the loop, as it means all elements from array2 have been placed.
    • Compare the current elements pointed by index1 and index2 of array1 and array2 respectively.
    • Place the larger element at the current position i in array1 and decrement the respective index (index1 or index2).

This approach ensures that the larger elements are placed at the end of array1 first, making efficient use of space while preserving the sorted order. This solution is efficient and executes in linear time relative to the total number of elements, or O(n + m), where n is the number of elements in array1 and m is the number of elements in array2.

js
var mergeArrays = function (array1, len1, array2, len2) {
    let index1 = len1 - 1;
    let index2 = len2 - 1;
    for (let position = len1 + len2 - 1; position >= 0; position--) {
        if (index2 < 0) {
            break;
        }
        if (index1 >= 0 && array1[index1] > array2[index2]) {
            array1[position] = array1[index1--];
        } else {
            array1[position] = array2[index2--];
        }
    }
};

Merge two sorted arrays in-place in a predefined space within the first array. The function mergeArrays efficiently tackles this with the following steps:

  1. Initialize two pointers index1 and index2 to point to the end of the actual elements in array1 and array2, respectively.
  2. Begin a reverse iteration from the total length of both arrays combined.
  3. Compare elements from the end of both arrays:
    • If the current element in array1 is larger, place it in the current position and decrement the index1.
    • Otherwise, place the element from array2 and decrement index2.
  4. Exit earlier if array2 is exhaustively merged, indicated by index2 being less than zero.

This function ensures optimal integration of two arrays by filling the first array from the end, thereby avoiding the overhead of moving unmerged elements with each insertion.

python
class Solution:
    def combine(self, first_list: List[int], len1: int, second_list: List[int], len2: int) -> None:
        # Initialize pointers for the merge process
        first_ptr = len1 - 1
        second_ptr = len2 - 1

        # Start from the end of the first list and fill backwards
        for idx in range(len1 + len2 - 1, -1, -1):
            if second_ptr < 0:
                break
            if first_ptr >= 0 and first_list[first_ptr] > second_list[second_ptr]:
                first_list[idx] = first_list[first_ptr]
                first_ptr -= 1
            else:
                first_list[idx] = second_list[second_ptr]
                second_ptr -= 1

The provided Python code defines a method to merge two pre-sorted integer arrays. This method, named combine, modifies the first array first_list in place by integrating elements from second_list, resulting in a single, fully merged and sorted array.

  • Memory Efficiency: The merging happens in-place on the first_list utilizing the extra space at its end, which ensures that no additional storage is needed.

  • Merging Logic: The solution uses three pointers:

    • first_ptr starts at the end of the actual elements in first_list (ignoring the extra space).
    • second_ptr starts at the end of second_list.
    • idx is used for setting the next value in first_list starting from the end towards the beginning.
  • Process Details:

    • The function fills first_list by comparing values from the end of both first_list and second_list, copying the larger value into the current position pointed by idx.
    • Decrement the pointers (first_ptr or second_ptr) accordingly.
    • The loop stops when all elements of second_list have been merged, assuming there's enough space in first_list.

Ensure to have the appropriate length setup (i.e., both len1 and the reserve space for second_list included in first_list) before calling this function to avoid errors. The function is particularly optimal when you need to integrate two lists without additional memory overhead, typical in scenarios like merging logs, event streams, or sorted data from different sources directly into a designated buffer space.

Comments

No comments yet.