Convert Min-Heap to Max-Heap

Posted: 13 Jul, 2020
Difficulty: Moderate


Try Problem

You are given an array/list (arr) representing a min-heap. Your task is to write a function that converts the min-heap to a max-heap.

 Note :
Change in the input array/list itself. You don't need to return or print the elements.
Input format :
The first line contains an integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.

The first line of each test case or query contains an integer 'N' representing the size of the array/list.

The second line contains 'N' single space separated integers representing the elements in the array/list which are in the form of a min-heap.
Output Format :
For each test case or query, If the built max-heap satisfies the max-heap condition, print 'true'. Otherwise, print 'false'(without quotes).

Output for every test case will be printed in a separate line.
 Note :
You don't have to print anything, it has already been taken care. Build the max-heap in the given array/list itself or in-place
Constraints :
1 <= t <= 100
0 <= N <= 10^5

Time Limit: 1 sec
Approach 1

For this approach, we will first copy the elements of the min-heap array to a soon-to-be-max-heap array using a for-loop. After copying each element to the max-heap array, we will heapify it to move it to its correct position. Following is the procedure for heapifying:

1. For every index in the heap, find its left child and right child. This can be done by calculating 2i + 1 and 2i + 2 where i is the index of the current element

2. Then find the maximum element among the left and right children and the current element.

3. If the current element is the maximum, then we will move on to the next index, otherwise, we will the swap the current element with the maximum element and recurse the heapify function on the maximum element

Try Problem