Merge two binary Max heaps | Practice | GeeksforGeeks

Given two binary max heaps as arrays, merge the given heaps to form a new max heap.
 
Example 1:
Input  : 
n = 4 m = 3
a[] = {10, 5, 6, 2}, 
b[] = {12, 7, 9}
Output : 
{12, 10, 9, 2, 5, 7, 6}
Explanation :




 
 
Your Task:  
You don't need to read input or print anything. Your task is to complete the function mergeHeaps() which takes the array a[], b[], its size n and m, as inputs and return the merged max heap. Since there can be multiple solutions, therefore, to check for the correctness of your solution, your answer will be checked by the driver code and will return 1 if it is correct, else it returns 0.
 
Expected Time Complexity: O(n.Logn)
Expected Auxiliary Space: O(n + m)
 
Constraints:
1 <= n, m <= 105
1 <= a[i], b[i] <= 2*105
 

 
 
0
rayalravi20011 week ago
c++ solution
 
   priority_queue<int>pq(a.begin(),a.end());       for(auto i: b){           pq.push(i);       }       vector<int>res;       while(!pq.empty()){           res.push_back(pq.top());           pq.pop();       }       return res;
+1
superdude2 weeks ago
Well the arrays are somewhat sorted so we can simply merge them like merging two sorted arrays. This algorithm might not be exactly what one wants when they ask you to do this question but it is a solution.
+1
koulikmaity3 weeks ago
void heapify(vector<int> &arr, int n, int i){   int largest = i;   int left = 2 * i + 1;   int right = 2 * i + 2;
   if (left < n && arr[left] > arr[largest])       largest = left;
   if (right < n && arr[right] > arr[largest])       largest = right;
   if (largest != i)   {       swap(arr[i], arr[largest]);       heapify(arr, n, largest);   }}   vector<int> mergeHeaps(vector<int> &a, vector<int> &b, int n, int m) {              // merge two vector in a single vector       vector<int> ans;              for(auto i: a)       {           ans.push_back(i);                   }       for(auto i: b)       {           ans.push_back(i);       }                     // then call heapify function       int size = ans.size();       for(int i=size/2 - 1; i>=0; i--)       {           heapify(ans, size, i);       }              return ans;   }
+2
dugguanshuman1 month ago
Simple solution without using priority_queue STL:
void insert_heap(vector <int> &arr, int i){
        if(i==1)
            return;
        if(arr[i/2-1]<arr[i-1]){
            swap(arr[i-1], arr[i/2-1]);
            insert_heap(arr, i/2);
        }
    }
    vector<int> mergeHeaps(vector<int> &a, vector<int> &b, int n, int m) {
        while(!b.empty()){
            a.push_back(b.back());
            b.pop_back();
            insert_heap(a, a.size());
        }
        return a;
    }
0
harshchittora20012 months ago
C++ SOLUTION USING PRIORITY_QUEUE
 
vector<int> mergeHeaps(vector<int> &a, vector<int> &b, int n, int m) {       // your code here       priority_queue<int>m1(a.begin(),a.end());       priority_queue<int>m2(b.begin(),b.end());       vector<int>v;       while(!m2.empty())       {           m1.push(m2.top());           m2.pop();       }       while(!m1.empty())       {           v.push_back(m1.top());           m1.pop();       }       return v;   }
0
singh_manish2 months ago
class Solution{   public:   void Heapify(int arr[], int i, int n)   {       int j = 2 * i + 1;       while (j < n)       {           if (j + 1 < n && arr[j + 1] > arr[j])               j++;           if (arr[j] > arr[i])           {               swap(arr[j], arr[i]);               i = j;               j = 2 * i + 1;           }           else               break;       }   }      vector<int> mergeHeaps(vector<int> &a, vector<int> &b, int n, int m) {       // your code here       vector<int> ans;       int v[n + m];          for (int i = 0; i < n; i++)           v[i] = a[i];       for (int i = 0; i < m; i++)           v[i + n] = b[i];       for (int i = n+m; i >= 0; i--)           Heapify(v, i, n + m);       for (int i = 0; i < n + m; i++)           ans.push_back(v[i]);       return ans;   }};
0
patildhiren442 months ago
Java - 1.3
public int[] mergeHeaps(int[] a, int[] b, int n, int m) {
        // your code here
       PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

        for (int i = 0; i < a.length; i++) {
            pq.add(a[i]);
        }

        for (int i = 0; i < b.length; i++) {
            pq.add(b[i]);
        }
        
        int[]res = new int[n+m];
        int ind=0;
        while(!pq.isEmpty()){
            res[ind] = pq.remove();
            ind++;
        }
        return res;
    }
+1
yashchawla1162 months ago
Simple To Understand And Easy To Implement.
 
https://yashboss116.blogspot.com/2022/03/merge-two-binary-max-heaps-geeks-for.html
 
-1
ayushnautiyal11103 months ago
vector<int> mergeHeaps(vector<int> &a, vector<int> &b, int n, int m) {      for(int i=0;i<m;i++){          a.push_back(b[i]);      }      sort(a.begin(),a.end());      reverse(a.begin(),a.end());      return a;   }
+2
aloksinghbais023 months ago
C++ solution having time complexity as O(N*log(N)) and space complexity as O(N+M) is as follows :- 
 
Execution Time :- 0.8 / 2.1 sec
 
void heapify(vector<int> &arr,int n,int i){       while(true){           int largest = i;           int left = 2*i+1;           int right = 2*i+2;                      if(left < n && arr[left] > arr[largest]){               largest = left;           }                      if(right < n && arr[right] > arr[largest]){               largest = right;           }                      if(largest != i){               swap(arr[i],arr[largest]);               i = largest;           }           else{               break;           }       }   }      vector<int> mergeHeaps(vector<int> &a, vector<int> &b, int n, int m) {       vector<int> ans(a);       for(auto x: b) ans.push_back(x);       for(int i = ans.size()/2 - 1; i >= 0; i--){           heapify(ans,ans.size(),i);       }       return (ans);   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.