![]() |
VOOZH | about |
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:
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:
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)