VOOZH about

URL: https://www.geeksforgeeks.org/dsa/merge-two-binary-max-heaps/

⇱ Merge Two Binary Max Heaps - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Merge Two Binary Max Heaps

Last Updated : 23 Jul, 2025

Given two binary max heaps, the task is to merge the given heaps to form a new max heap.

Examples :

Input: a[] = {10, 5, 6, 2}, b[] = {12, 7, 9}
Output: {12, 10, 9, 2, 5, 7, 6}

👁 Merge-two-max-heaps-(1)
Merge Two Binary Max Heaps

Input: a[] = {2, 5, 1, 9, 12}, b[] = {3, 7, 4, 10}
Output: {12, 10, 7, 9, 5, 3, 1, 4, 2}

[Naive Approach] Merge using extra Max Heap - O((N + M)*log(N + M)) Time and O(N + M) Space:

The property of Max Heap is that the top of any Max Heap is always the largest element. We will use this property to merge the given binary Max Heaps.

To do this:

  • Create another Max Heap, and insert the elements of given binary max heaps into this one by one.
    • Now repeat above step until all the elements from both given Max Heaps are merged into the third one, ensuring the property of largest element on top (max heapify).
  • The third Max Heap will be the required merged Binary Max Heap.

Below is the implementation of the above approach:


Output
12 10 9 7 6 5 2 

Time Complexity: O((N + M)*log(N + M)), where N is the size of a[] and M is the size of b[].

  • Since we are fetching one element after the other from given max heaps, the time for this will be O(N + M)
  • Now for each element, we are doing max heapify on the third heap. This heapify operation for element of the heap will take O(log N+M) each time
  • Therefore the resultant complexity will be O(N+M)*(log (N+M))

Auxiliary Space: O(N + M), which is the size of the resultant merged binary max heap

[Expected Approach] Merge and then Build Heap - O(N + M) Time and O(N + M) Space:

Another approach is that instead of creating a max heap from the start, flatten the given max heap into arrays and merge them. Then max heapify this merged array.

The benefit of doing so, is that, instead of taking O(log N+M) time everytime to apply heapify operation as shown in above approach, this approach will take only O(N+M) time once to build the final heap.

Below is the implementation of the above approach:


Output
12 10 9 2 5 7 6 

Time Complexity: O(N + M)
Auxiliary Space: O(N + M)

Time Complexity: O(N + M), where N is the size of a[] and M is the size of b[].

  • Time taken to flatten first binary heap is O(N), which is already provided as input
  • Time taken to flatten second binary heap is O(M), which is already provided as input
  • Time for merging two arrays = O(N+M)
  • Time to build max heap from merged array = O(N+M)
  • Therefore the resultant complexity will be O(N+M)

Auxiliary Space: O(N + M), which is the size of the resultant merged binary max heap

Comment
Article Tags: