Last Updated: 2 Apr, 2021

Convert Min Heap To Max Heap

Moderate
Asked in companies
AmazonSAP LabsOLX Group

Problem statement

You are given an array of size ‘N’ which is an array representation of min-heap.


You need to convert this min-heap array representation to a max-heap array representation. Return the max-heap array representation.


For Example
Corresponding to given min heap : [1,2,3,6,7,8]

It can be converted to the following max heap: [8,7,3,6,2,1]

Input Format:
The first line contains a single integer ‘N’ denoting the size of the array.

The next line contains ‘N’ space-separated integers denoting the array representation of min-heap.
Output Format
There can be many possible max-heaps. Return any possible max-heap for given input min-heap.

Approaches

01 Approach

The main idea is that when an array is sorted in descending order it becomes max heap as for every ‘i’ from i=0 to n/2 it is greater than equal to arr[2*i+1] and arr[2*i+2].

02 Approach

The main idea is to build max-heap for the given input array just like in heapsort. It will convert the input array into a max heap. We will perform the heapify(Refer Heap Sort Algorithm) process to the given input array to build the heap. In a max heap, if arr[ i ] is less than it’s it children node arr[2*i+1] and arr[2*i+2] then replace it with children and call heapfiy on the corresponding child node.Heapify can only be applied to a node only when its children are heapified. Hence it must be performed in bottom-up order.