HomeLeetcodeMerge Sorted Array (Task 88) - Solutions

Merge Sorted Array (Task 88) – Solutions

Description:

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.

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.

Solution in Python:

To solve this problem, we need to merge two sorted arrays, nums1 and nums2, into one sorted array in-place within nums1. The key insight is to start merging from the end of nums1 to avoid overwriting elements that haven’t been processed yet. We’ll use a three-pointer approach: one pointer for nums1, one for nums2, and one for the position in the merged array.

Python
from typing import List

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Merge nums2 into nums1 in-place. The final sorted array should not be returned
        by the function, but instead be stored inside the array nums1.
        """
        # Start from the end of nums1 and nums2
        p1 = m - 1  # Pointer for the last element in nums1's initial elements
        p2 = n - 1  # Pointer for the last element in nums2
        p_merge = m + n - 1  # Pointer for the last position in nums1
        
        # Compare elements from nums1 and nums2 and fill nums1 from the end
        while p1 >= 0 and p2 >= 0:
            if nums1[p1] > nums2[p2]:
                nums1[p_merge] = nums1[p1]
                p1 -= 1
            else:
                nums1[p_merge] = nums2[p2]
                p2 -= 1
            p_merge -= 1
        
        # If there are remaining elements in nums2, place them in nums1
        # No need to check for nums1 because they are already in place
        while p2 >= 0:
            nums1[p_merge] = nums2[p2]
            p_merge -= 1
            p2 -= 1

# Example usage:
sol = Solution()
nums1 = [1,2,3,0,0,0]
m = 3
nums2 = [2,5,6]
n = 3
sol.merge(nums1, m, nums2, n)
print(nums1)  # Output: [1, 2, 2, 3, 5, 6]

Explanation:

  1. Initialization:
    • p1 is initialized to m - 1, which is the index of the last element in the initial part of nums1.
    • p2 is initialized to n - 1, which is the index of the last element in nums2.
    • p_merge is initialized to m + n - 1, which is the index of the last position in nums1.
  2. Merging:
    • We iterate through nums1 and nums2 from the end, comparing elements and placing the larger one at the current position pointed to by p_merge.
    • We decrease the appropriate pointers (p1, p2, p_merge) after each operation.
  3. Handling Remaining Elements:
    • If p2 still has elements left after the main loop, we copy them into nums1 at the appropriate positions.
    • If p1 has elements left, they are already in their correct positions, so no action is needed.

This approach ensures we don’t overwrite any elements before they are processed and efficiently merges the two arrays in-place.

Solution in Javascript:

JavaScript
/**
 * Merges two sorted arrays into one sorted array in-place.
 * @param {number[]} nums1 - The first sorted array, which has a length of m + n.
 * @param {number} m - The number of initialized elements in nums1.
 * @param {number[]} nums2 - The second sorted array.
 * @param {number} n - The number of elements in nums2.
 * @return {void} Do not return anything, modify nums1 in-place instead.
 */
var merge = function(nums1, m, nums2, n) {
    // Initialize three pointers
    let p1 = m - 1; // Pointer for the last initialized element in nums1
    let p2 = n - 1; // Pointer for the last element in nums2
    let pMerge = m + n - 1; // Pointer for the last position in nums1
    
    // Compare elements from the end of nums1 and nums2 and place them in the correct position
    while (p1 >= 0 && p2 >= 0) {
        if (nums1[p1] > nums2[p2]) {
            nums1[pMerge] = nums1[p1];
            p1--;
        } else {
            nums1[pMerge] = nums2[p2];
            p2--;
        }
        pMerge--;
    }
    
    // If there are any remaining elements in nums2, copy them over to nums1
    while (p2 >= 0) {
        nums1[pMerge] = nums2[p2];
        pMerge--;
        p2--;
    }
};

// Example usage:
let nums1 = [1, 2, 3, 0, 0, 0];
let m = 3;
let nums2 = [2, 5, 6];
let n = 3;
merge(nums1, m, nums2, n);
console.log(nums1); // Output: [1, 2, 2, 3, 5, 6]

Solution in Java:

Java
class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        // Initialize three pointers
        int p1 = m - 1; // Pointer for the last initialized element in nums1
        int p2 = n - 1; // Pointer for the last element in nums2
        int pMerge = m + n - 1; // Pointer for the last position in nums1
        
        // Compare elements from the end of nums1 and nums2 and place them in the correct position
        while (p1 >= 0 && p2 >= 0) {
            if (nums1[p1] > nums2[p2]) {
                nums1[pMerge] = nums1[p1];
                p1--;
            } else {
                nums1[pMerge] = nums2[p2];
                p2--;
            }
            pMerge--;
        }
        
        // If there are any remaining elements in nums2, copy them over to nums1
        while (p2 >= 0) {
            nums1[pMerge] = nums2[p2];
            pMerge--;
            p2--;
        }
        
        // No need to copy the remaining elements from nums1 since they are already in place
    }
    
    public static void main(String[] args) {
        Solution sol = new Solution();
        
        int[] nums1 = {1, 2, 3, 0, 0, 0};
        int m = 3;
        int[] nums2 = {2, 5, 6};
        int n = 3;
        sol.merge(nums1, m, nums2, n);
        System.out.println(java.util.Arrays.toString(nums1)); // Output: [1, 2, 2, 3, 5, 6]
    }
}

Solution in C#:

C#
using System;

public class Solution {
    public void Merge(int[] nums1, int m, int[] nums2, int n) {
        // Initialize three pointers
        int p1 = m - 1; // Pointer for the last initialized element in nums1
        int p2 = n - 1; // Pointer for the last element in nums2
        int pMerge = m + n - 1; // Pointer for the last position in nums1
        
        // Compare elements from the end of nums1 and nums2 and place them in the correct position
        while (p1 >= 0 && p2 >= 0) {
            if (nums1[p1] > nums2[p2]) {
                nums1[pMerge] = nums1[p1];
                p1--;
            } else {
                nums1[pMerge] = nums2[p2];
                p2--;
            }
            pMerge--;
        }
        
        // If there are any remaining elements in nums2, copy them over to nums1
        while (p2 >= 0) {
            nums1[pMerge] = nums2[p2];
            pMerge--;
            p2--;
        }
        
        // No need to copy the remaining elements from nums1 since they are already in place
    }
}

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments

Popular