VOOZH about

URL: https://www.geeksforgeeks.org/dsa/merge-two-sorted-arrays/

⇱ Merge two sorted arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Merge two sorted arrays

Last Updated : 31 Jul, 2025

Given two sorted arrays arr1[] of size n and arr2[] of size m. Merge these two arrays.
After the merge, the first n smallest elements of the combined sorted array should be stored in arr1[], and the remaining m largest elements should be stored in arr2[]. After the merging process, both arr1[] and arr2[] must remain sorted in non-decreasing order.
Examples:

Input: arr1[] = [1, 3, 4, 5], arr2[] = [2, 4, 6, 8] 
Output: arr1[] = [1, 2, 3, 4], arr2[] = [4 5, 6, 8] 
Explanation: Combined sorted array = [1, 2, 3, 4, 4, 5, 6, 8], array arr1[] contains smallest 4 elements: 1, 2, 3, 4, and array arr2[] contains the remaining 4 elements: 4, 5, 6, 8.

Input: arr1[] = [5, 8, 9], arr2[] = [4, 7, 8] 
Output: arr1[] = [4, 5, 7], arr2[] = [8, 8, 9] 
Explanation: Combined sorted array = [4, 5, 7, 8, 8, 9], array arr1[] contains smallest 3 elements: 4, 5, 7, and array arr2[] contains the remaining 3 elements: 8, 8, 9.

[Naive Approach] Concatenate and Sort - O((n + m) log(n + m)) Time and O(n + m) Space

The idea is to combine both sorted arrays into a single temporary array, then sort this combined array to get all elements in non-decreasing order. Once sorted, the first n smallest elements are copied back into arr1, and the remaining m largest elements are placed into arr2.


Output
1 2 3 4 
5 6 7 8 

[Expected Approach] Two Pointer Merge - O(n + m) Time and O(n + m) Space

The idea is to use the two-pointer to merge both sorted arrays into a temporary array in linear time. We compare elements from arr1 and arr2 one by one and append the smaller element to the merged array. After merging, we copy the first n elements back to arr1 and the remaining m elements to arr2.

Step-by-Step Implementation:

  • Initialize two pointers: i = 0 for traversing arr1, j = 0 for traversing arr2
  • Create an empty array merged = []
  • Merge the elements into merged: While both i < n and j < m:
    => If arr1[i] <= arr2[j], append arr1[i] to merged and increment i
    => Else, append arr2[j] to merged and increment j
  • Append remaining elements (if any):
    => While i < n, append arr1[i] to merged and increment i
    => While j < m, append arr2[j] to merged and increment j
  • Distribute the merged elements back:
    => Copy the first n elements of merged to arr1
    => Copy the remaining m elements to arr2

Output
1 2 3 4 
5 6 7 8 

Problems related to Merging Two Sorted Arrays

Merge two sorted arrays with O(1) extra space
Merge k sorted arrays
Union of Two Sorted Arrays
Intersection of Two Sorted Arrays
Merge 2 sorted linked list in reverse order
Sort last M elements
Merge 2 sorted linked list in reverse order
Merge Sort for Doubly Linked List

Comment
Article Tags: