VOOZH about

URL: https://www.geeksforgeeks.org/dsa/merge-two-sorted-arrays-in-constant-space-using-min-heap/

⇱ Merge two sorted arrays in constant space using Min Heap - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Merge two sorted arrays in constant space using Min Heap

Last Updated : 12 Jul, 2025

Given two sorted arrays, we need to merge them with O(1) extra space into a sorted array, when N is the size of the first array, and M is the size of the second array.

Example

:

Input: arr1[] = {10};
arr2[] = {2, 3};
Output: arr1[] = {2}
arr2[] = {3, 10}
Input: arr1[] = {1, 5, 9, 10, 15, 20};
arr2[] = {2, 3, 8, 13};
Output: arr1[] = {1, 2, 3, 5, 8, 9}
arr2[] = {10, 13, 15, 20}

We had already discussed two more approaches to solve the above problem in constant space:

In this article, one more approach using the concept of the heap data structure is discussed without taking any extra space to merge the two sorted arrays. Below is the detailed approach in steps:

  1. The idea is to convert the second array into a min-heap first. This can be done in O(M) time complexity.
  2. After converting the second array to min-heap:
    • Start traversing the first array and compare the current element for the first array to top of the created min_heap.
    • If the current element in the first array is greater than heap top, swap the current element of the first array with the root of the heap, and heapify the root of the min_heap.
    • After performing the above operation for every element of the first array, the first array will now contain first N elements of the sorted merged array.
  3. Now, the elements remained in the min_heap or the second array are the last M elements of the sorted merged array.
  4. To arrange them in sorted order, apply in-place heapsort on the second array.

Note

: We have used built-in STL functions available in C++ to convert array to min_heap, sorting the heap etc. It is recommended to read -

Heap in C++ STL | make_heap(), push_heap(), pop_heap(), sort_heap()

before moving on to the program. Below is the implementation of the above approach:


Output
After Merging :- 
First Array: 1 2 3 5 8 9 
Second Array: 10 13 15 20

Time Complexity

: O(N*logM + M*logN)

Auxiliary Space

: O(1)

Comment
Article Tags: