AlgoMaster Logo

Merge Sorted Array

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Merge Then Sort

Intuition:

The simplest approach to solve the problem is to first merge the elements of nums2 into nums1 and then sort nums1. Although it is not the most efficient solution, it works for small inputs and provides an easy starting point.

Steps:

  1. Copy all elements from nums2 into nums1 starting from index m.
  2. Sort the array nums1.

Code:

2. Two-Pointer

Intuition:

Both arrays nums1 and nums2 are sorted, thus we can use a two-pointer technique to merge them efficiently. Create a new array to store the merged sorted elements.

Steps:

  1. Initialize three pointers: p1 for nums1p2 for nums2, and p for the new array.
  2. Compare elements pointed by p1 and p2, and place the smaller one in the new array.
  3. If any elements are left in nums1 or nums2, append them to the end of the new array.
  4. Copy the new array back into nums1.

Code:

3. In-place Two-Pointer

Intuition:

Since the space in nums1 after m is unused, leverage this space to place the merged results directly. We'll move backwards from the end of the arrays to avoid overwriting any values.

Steps:

  1. Use two pointers p1 and p2 starting from the end of the initialized parts of nums1 and nums2 respectively, and another pointer p from the very end of nums1.
  2. Compare the current elements of nums1 and nums2 and place the larger one at the p position.
  3. Decrement the respective pointers.
  4. If any elements are left in nums2, copy them to nums1 (no need to handle the remaining nums1, they are already in place).

Code: