Related Articles

# Merge two sorted arrays in constant space using Min Heap

• Difficulty Level : Medium
• Last Updated : 25 Sep, 2019

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}
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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:

 `// C++ program to merge two sorted arrays in``// constant space`` ` `#include ``using` `namespace` `std;`` ` `// Function to merge two sorted arrays in``// constant space``void` `mergeArrays(``int``* a, ``int` `n, ``int``* b, ``int` `m)``{`` ` `    ``// Convert second array into a min_heap``    ``// using make_heap() STL function [takes O(m)]``    ``make_heap(b, b + m, greater<``int``>());`` ` `    ``// Start traversing the first array``    ``for` `(``int` `i = 0; i < n; i++) {`` ` `        ``// If current element is greater than root``        ``// of min_heap``        ``if` `(a[i] > b) {`` ` `            ``// Pop minimum element from min_heap using``            ``// pop_heap() STL function``            ``// The pop_heap() function removes the minimum element from``            ``// heap and moves it to the end of the container``            ``// converted to heap and reduces heap size by 1``            ``pop_heap(b, b + m, greater<``int``>());`` ` `            ``// Swapping the elements``            ``int` `tmp = a[i];``            ``a[i] = b[m - 1];``            ``b[m - 1] = tmp;`` ` `            ``// Apply push_heap() function on the container``            ``// or array to again reorder it in the``            ``// form of min_heap``            ``push_heap(b, b + m, greater<``int``>());``        ``}``    ``}`` ` `    ``// Convert the second array again into max_heap``    ``// because sort_heap() on min heap sorts the array``    ``// in decreasing order``    ``// This step is [O(m)]``    ``make_heap(b, b + m); ``// It's a max_heap`` ` `    ``// Sort the second array using sort_heap() function``    ``sort_heap(b, b + m);``}`` ` `// Driver Code``int` `main()``{`` ` `    ``int` `ar1[] = { 1, 5, 9, 10, 15, 20 };``    ``int` `ar2[] = { 2, 3, 8, 13 };``    ``int` `m = ``sizeof``(ar1) / ``sizeof``(ar1);``    ``int` `n = ``sizeof``(ar2) / ``sizeof``(ar2);``    ``mergeArrays(ar1, m, ar2, n);`` ` `    ``cout << ``"After Merging :- \nFirst Array: "``;``    ``for` `(``int` `i = 0; i < m; i++)``        ``cout << ar1[i] << ``" "``;``    ``cout << ``"\nSecond Array: "``;``    ``for` `(``int` `i = 0; i < n; i++)``        ``cout << ar2[i] << ``" "``;`` ` `    ``return` `0;``}`
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)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up