Skip to main content

Merge Two Sorted Arrays.

KANISHKA GUPTA
EditReport

Merge Two Sorted Arrays

Problem Description

Given two sorted arrays, the task is to merge them into a single sorted array. The input arrays may contain duplicates, and the final output should also be sorted. This problem is a common exercise in understanding array manipulation and is often used to illustrate the two-pointer technique.

Video Explanation

Example

  • Input:

    • arr1 = [1, 3, 5]
    • arr2 = [2, 4, 6]
  • Output:

    • [1, 2, 3, 4, 5, 6]

Approach

To merge the two sorted arrays efficiently, we can use the following approach:

  1. Initialize Two Pointers: Start with two pointers, one for each array, both set to zero.
  2. Compare Elements: Traverse both arrays and compare the current elements pointed to by the pointers.
    • If the element in the first array is smaller, add it to the merged array and increment the pointer for the first array.
    • If the element in the second array is smaller, add it to the merged array and increment the pointer for the second array.
  3. Handle Remaining Elements: Once one of the arrays is completely traversed, append any remaining elements from the other array to the merged array.
  4. Return the Merged Array: The final output will be a single sorted array containing all elements from both input arrays.

Time Complexity

The time complexity for this approach is (O(n + m)), where (n) and (m) are the lengths of the two input arrays.

Implementation

Solutions

class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int p1 = m - 1, p2 = n - 1, p = m + n - 1;
while (p1 >= 0 && p2 >= 0) {
if (nums1[p1] > nums2[p2]) {
nums1[p] = nums1[p1--];
} else {
nums1[p] = nums2[p2--];
}
p--;
}
while (p2 >= 0) {
nums1[p--] = nums2[p2--];
}
}
};
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

💬 Discuss this page

Have a question or spot something confusing in "Merge Two Sorted Arrays."? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.