Build Min Heap

Moderate
0/80
Average time to solve is 30m
profile
Contributed by
87 upvotes
Asked in companies
AdobeDunzoAmazon

Problem statement

You are given an array 'ARR' of integers having 'N' elements. Your task is to convert the input array into a min-Binary Heap.

A min-Binary heap is a complete binary tree in which the value of each internal node is smaller than or equal to the values of the children of that node.

Note :
1. Input array follows 0 - based indexing. 

2. After constructing the min-heap, the Left child of the 'i-th' node should be present at the (2*i + 1)-th index if it exists.

3. After constructing the min-heap, the Right child of the 'i-th' node should be present at the (2*i + 2)-th index if it exists.

4. Note that you do not need to create a tree, just update the array.
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line of the input contains an integer, 'T,’ denoting the number of test cases.

The first line of each test case contains an integer ‘N', denoting the number of elements in the array 'ARR'.

The second line of each test case contains 'N' space-separated integers denoting the array elements.
Output Format :
For each test case, the checker will print 1 if the returned array represents a valid min-heap. Otherwise, the checker will print 0.

The output of each test case will be printed on a new line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= N <= 10^4
-10^9 <= ARR[i] <= 10^9

Where 'ARR[i]' denotes the 'i-th' element of the array 'ARR'.

Time Limit: 1 sec
Sample Input 1 :
2
5
9 3 2 6 7 
4
1 3 2 4
Sample Output 1 :
1
1
Explanation For Sample Input 1 :
For the first test case:
One possible min-heap representation of the input array is the array [ 2, 3, 6, 7, 9 ]. Note that other arrays like [ 2, 6, 3, 9, 7 ], [ 2, 3, 6, 9, 7 ] also represent min-heap.

input

For the second test case: 

input

The input array is already a min-heap, so we do not need to modify it.
Sample Input 2 :
2
5
1 3 5 4 6
3
8 9 0
Sample Output 2 :
1 
1
Explanation For Sample Input 2 :
For the first test case:
One possible min-heap representation of the input array is the array [ 1, 3, 5, 4, 6 ] which is the same as the input array. 

For the second test case: 
One possible min-heap representation of the input array is the array [ 0, 8, 9 ].
Hint

Try to think of an approach that travels the array from right to left and recursively convert the array into a heap. 

Approaches (1)
Heapify Algorithm

The idea is to follow a top-down approach. The given array does not necessarily represent a heap. In order to convert the input array to a heap, we will heapify the complete binary tree formed from the array in reverse order, i.e., from the rightmost element to the leftmost element. Heapify is defined as the process of converting a binary tree into a Heap data structure. We do not need to heapify the leaf nodes as they are already heapified because they do not have any left child or right child. Note that the input array representation of the complete binary tree denotes the level order traversal of the tree. We need to find the position of the first non-leaf node from the right and perform the heapify operation of each node in reverse of the level order.

 

Heapify is the process of converting a binary tree into a Heap data structure. The heapify algorithm is a recursive algorithm that is used to heapify a node assuming that both the subtrees of the node are already heapified. In each step of heapification, we check whether the current node has a value smaller than both of its children ( if they exist ). If yes, then the node and the nodes in its corresponding subtree are already heapified. Otherwise, we swap the node with the child having a smaller value and call the heapify function recursively for that child as the subtree was changed, and now we will have to heapify it again. The recursive algorithm stops if the subtree is already heapified.

 

Algorithm

 

  • Set firstNonLeaf to ( N / 2 - 1 ). We are setting the index of the first non-leaf node as ( N / 2 - 1 ). Because in a complete binary tree having N nodes, the number of leaf nodes in it are ( N + 1) / 2, and all the leaf nodes are situated at rightmost positions in its level order traversal. We have already seen that it is not required to heapify leaf nodes, so we can directly move to the first non-leaf node.
  • Iterate from i = firstNonLeaf to 0.
    • Call heapify function for the i'th node of the array.
      • Define a variable smallestNode to store the index of the node having the smallest value among the current node and the left and the right child of the current node. Initialize it as i. 
      • Define the leftChild index as 2*i + 1 and the rightChild index as 2*i + 2. 
      • If leftChild is less than N and arr[leftChild] is smaller than arr[smallestNode], then update smallestNode to leftChild. In this step, we are checking if the current node's left children, if it exists, has a value smaller than its parent node and updating the smallestNode value accordingly.
      • If rightChild is less than N and arr[rightChild] is smaller than arr[smallestNode], then update smallestNode to rightChild. In this step, we are checking if the current node's right children, if it exists, has a value smaller than its parent node and updating the smallestNode value accordingly.
      • If smallestNode is not equal to i, then we will swap arr[smallestNode] with arr[i] and call the heapify algorithm for smallestNode. We are calling heapify here because when we are swapping the two values, then there may be a possibility that the updated subtree is not heapified. Hence, we need to heapify it again.
  • Return the modified input array.
Time Complexity

O(N), where ‘N’ is the number of elements in the array.

 

A heap of size N has at most ceil ( N / 2^(h+1) ) nodes with height h. The heapify algorithm for a node takes time proportional to its height in the worst case. The total number of iterations to heapify each node will be the summation of ( ceil ( N /  2^(h+1) ) * h ) over all values of h ( i.e. from 0 to log(N) ), which turns out to be 2*N. Hence, the overall Time Complexity will be O(N).

Space Complexity

O(log(N)), where ‘N’ is the number of elements in the array.

 

In the worst case, when the input array is a max-heap. The recursion depth will be equal to the complete binary tree’s height, i.e., log(N). Hence, the overall Space Complexity will be O(log(N)).

Code Solution
(100% EXP penalty)
Build Min Heap
Full screen
Console