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:
- Merge two sorted arrays with O(1) extra space.
- Efficiently merging two sorted arrays with O(1) extra 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:
- The idea is to convert the second array into a min-heap first. This can be done in O(M) time complexity.
- 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.
- Now, the elements remained in the min_heap or the second array are the last M elements of the sorted merged array.
- 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:
CPP14
// C++ program to merge two sorted arrays in// constant spaceÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to merge two sorted arrays in// constant spacevoid 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[0]) {Â
            // 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 Codeint main(){Â
    int ar1[] = { 1, 5, 9, 10, 15, 20 };    int ar2[] = { 2, 3, 8, 13 };    int m = sizeof(ar1) / sizeof(ar1[0]);    int n = sizeof(ar2) / sizeof(ar2[0]);    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;} |
Java
// Nikunj Sonigaraimport java.util.*;Â
public class Main {         // Function to merge two sorted arrays in constant space    public static void mergeArrays(int[] a, int n, int[] b, int m) {                 // Convert the second array into a min heap        PriorityQueue<Integer> minHeap = new PriorityQueue<>();        for (int value : b) {            minHeap.offer(value);        }                 // Start traversing the first array        for (int i = 0; i < n; i++) {                         // If the current element is greater than the root of the min heap            if (a[i] > minHeap.peek()) {                                 // Remove and retrieve the minimum element from the min heap                int min = minHeap.poll();                                 // Swap the elements                int tmp = a[i];                a[i] = min;                minHeap.offer(tmp);            }        }                 // Convert the min heap (second array) back to an array        int index = 0;        while (!minHeap.isEmpty()) {            b[index++] = minHeap.poll();        }                 // Sort the second array        Arrays.sort(b);    }         // Driver Code    public static void main(String[] args) {        int[] ar1 = { 1, 5, 9, 10, 15, 20 };        int[] ar2 = { 2, 3, 8, 13 };        int m = ar1.length;        int n = ar2.length;                 mergeArrays(ar1, m, ar2, n);Â
        System.out.println("After Merging :- \nFirst Array: " + Arrays.toString(ar1));        System.out.println("Second Array: " + Arrays.toString(ar2));    }} |
Python
# Nikunj SonigaraÂ
import heapqÂ
# Function to merge two sorted arrays in constant spacedef mergeArrays(a, n, b, m):         # Convert the second array into a min heap    heapq.heapify(b)         # Start traversing the first array    for i in range(n):                 # If the current element is greater than the root of the min heap        if a[i] > b[0]:                         # Pop the minimum element from the min heap            min_val = heapq.heappop(b)                         # Swap the elements            a[i], min_val = min_val, a[i]                         # Push the swapped value back to the min heap            heapq.heappush(b, min_val)         # Sort the second array    heapq.heapify(b) # Convert the min heap back to a heap    b.sort()Â
# Driver Codeif __name__ == "__main__":Â Â Â Â ar1 = [1, 5, 9, 10, 15, 20]Â Â Â Â ar2 = [2, 3, 8, 13]Â Â Â Â m = len(ar1)Â Â Â Â n = len(ar2)Â Â Â Â Â Â Â Â Â mergeArrays(ar1, m, ar2, n)Â
    print("After Merging :- \nFirst Array: ", ar1)    print("Second Array: ", ar2) |
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)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
