Given array representation of min Heap, convert it to max Heap in O(n) time.
Input: arr = [3 5 9 6 8 20 10 12 18 9] 3 / \ 5 9 / \ / \ 6 8 20 10 / \ / 12 18 9 Output: arr = [20 18 10 12 9 9 3 5 6 8] OR [any Max Heap formed from input elements] 20 / \ 18 10 / \ / \ 12 9 9 3 / \ / 5 6 8
The problem might look complex at first look. But our final goal is to only build the max heap. The idea is very simple – we simply build Max Heap without caring about the input. We start from bottom-most and rightmost internal mode of min Heap and heapify all internal modes in bottom up way to build the Max heap.
Below is its implementation
Min Heap array : 3 5 9 6 8 20 10 12 18 9 Max Heap array : 20 18 10 12 9 9 3 5 6 8
The complexity of above solution might looks like O(nLogn) but it is O(n). Refer this G-Fact for more details.
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
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.
- Difference between Min Heap and Max Heap
- Heap Sort for decreasing order using min heap
- Difference between Binary Heap, Binomial Heap and Fibonacci Heap
- Convert BST to Max Heap
- Convert BST to Min Heap
- Minimum element in a max heap
- Max Heap in Java
- K-th Greatest Element in a Max-Heap
- Max Heap in Python
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Merge k sorted linked lists | Set 2 (Using Min Heap)
- Print all nodes less than a value x in a Min Heap.
- Maximum element in min heap
- Fibonacci Heap - Deletion, Extract min and Decrease key
- K’th Least Element in a Min-Heap
- Maximise the number of toys that can be purchased with amount K using min Heap
- Merge two sorted arrays in constant space using Min Heap
- Min Heap in Python
- Complexity analysis of various operations of Binary Min Heap
- k largest(or smallest) elements in an array | added Min Heap method