Binary Heap Operations | Practice | GeeksforGeeks

A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey,  deleteKey,  and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1  x  (a query of this type means to insert an element in the min-heap with value x )
2) 2  x  (a query of this type means to remove an element at position x from the min-heap)
3) 3  (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query 
insertKey(4) the heap will have  {4}  
insertKey(2) the heap will be {2 4}
extractMin() removes min element from 
             heap ie 2 and prints it
             now heap is {4} 
insertKey(6) inserts 6 to heap now heap
             is {4 6}
deleteKey(0) delete element at position 0
             of the heap,now heap is {6}
extractMin() remove min element from heap
             ie 6 and prints it  now the
             heap is empty
extractMin() since the heap is empty thus
             no min element exist so -1
             is printed.

Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 104
1 <= x <= 104
0
2020aspire503 months ago
int MinHeap::extractMin() {   if(heap_size<=0)return -1;   if(heap_size==1)   {       heap_size--;       return harr[0];   }   swap(harr[0],harr[heap_size-1]);   heap_size--;   MinHeapify(0);   return harr[heap_size];}
//Function to delete a key at ith index.void MinHeap::deleteKey(int i){   if(i>=heap_size||heap_size<=0)return;   decreaseKey(i,INT_MIN);   extractMin();}
//Function to insert a value in Heap.void MinHeap::insertKey(int k) {   if(heap_size==capacity)return;   heap_size++;   harr[heap_size-1]=k;   int i=heap_size-1;   while(i!=heap_size&&harr[i]<harr[parent(i)])   {       swap(harr[i],harr[parent(i)]);       i=parent(i);   }}
//Function to change value at ith index and store that value at first index.void MinHeap::decreaseKey(int i, int new_val) {      harr[i]=new_val;   while(i!=0&&harr[parent(i)]>harr[i])   {   swap(harr[parent(i)],harr[i]);     i=parent(i);   }}void MinHeap::MinHeapify(int i) {  int lt=left(i);  int rt=right(i);  int smallest=i;  if(heap_size>lt&&harr[lt]<harr[i])  smallest=lt;  if(heap_size>rt&&harr[rt]<harr[smallest])  smallest=rt;  if(i!=smallest)  {      swap(harr[smallest],harr[i]);      MinHeapify(smallest);  }} 
0
19it020anku4 months ago
int MinHeap::extractMin() {   // Your code here     if(heap_size==0)   return -1;   if(heap_size==1){       heap_size--;   return harr[0];   }    swap(harr[0],harr[heap_size-1]);    heap_size--;    MinHeapify(0);    return harr[heap_size];}
//Function to delete a key at ith index.void MinHeap::deleteKey(int i){   // Your code here     if(heap_size<=0||heap_size<=i)      return;      decreaseKey(i,INT_MIN);      extractMin();}
//Function to insert a value in Heap.void MinHeap::insertKey(int k) {   // Your code here        if(heap_size>=capacity)    return;    heap_size++;    harr[heap_size-1]=k;    for(int i=heap_size-1;i!=0 && harr[parent(i)]>harr[i];)    {        swap(harr[parent(i)],harr[i]);        i=parent(i);    }}
//Function to change value at ith index and store that value at first index.void MinHeap::decreaseKey(int i, int new_val) {   harr[i] = new_val;   while (i != 0 && harr[parent(i)] > harr[i]) {       swap(harr[i], harr[parent(i)]);       i = parent(i);   }}
+3
bijayshaw6354 months ago
int extractMin(){       if(heap_size<=0){           return -1;       }       if(heap_size==1){           heap_size--;           return harr[0];       }       int answer=harr[0];       harr[0]=harr[heap_size-1];       heap_size--;        MinHeapify(0);       return answer;   }   void insertKey(int k){       if(heap_size==capacity){           return;       }       heap_size++;       int i=heap_size-1;       harr[i]=k;       while(i!=0 && harr[parent(i)]>harr[i]){           int temp=harr[parent(i)];           harr[parent(i)]=harr[i];           harr[i]=temp;           i=parent(i);       }   }   void deleteKey(int i){       if(i>heap_size-1){           return;       }       decreaseKey(i,Integer.MIN_VALUE);       extractMin();   }
0
iamx72784 months ago
int MinHeap::extractMin() {  if(heap_size==0) return -1;  if(heap_size==1) {heap_size--; return harr[0];}  swap(harr[0],harr[heap_size-1]);  heap_size--;  MinHeapify(0);  return harr[heap_size];}void MinHeap::deleteKey(int i){   if(heap_size<=0 || heap_size<=i) return;   decreaseKey(i,INT_MIN);   extractMin();}void MinHeap::insertKey(int k) {   if(heap_size>=capacity)return;   heap_size++;   decreaseKey(heap_size-1,k);}
0
singhsrijan8094 months ago
Java solution 09.sec
 
PLAYERG SOLUTION
class MinHeap {   int[] harr;   int capacity,  heap_size;   MinHeap(int cap) {       heap_size = 0;       capacity = cap;       harr = new int[cap];   }   int parent(int i) { return (i - 1) / 2; }   int left(int i) { return (2 * i + 1); }   int right(int i) { return (2 * i + 2); }
   //Function to extract minimum value in heap and then to store    //next minimum value at first index.       public void swap(int[] harr,int parent, int i) { // TODO Auto-generated method stub int temp=harr[parent]; harr[parent]=harr[i]; harr[i]=temp;}   int extractMin()   {       // Your code here.      if(heap_size==0)           return -1;       if(heap_size==1) {        heap_size--;        return harr[heap_size];       }       swap(harr,0,heap_size-1);       heap_size--;       MinHeapify(0);       return harr[heap_size];          }
   //Function to insert a value in Heap.   void insertKey(int k)    {         // Your code here.if(heap_size>=capacity)         return;       heap_size++;       int i=heap_size-1;       harr[i]=k;       while(i!=0 && harr[parent(i)]>harr[i]) {           swap(harr,parent(i),i);           i=parent(i);       }   }
   //Function to delete a key at ith index.   void deleteKey(int i)    {       if(heap_size<=0 || i>=heap_size)           return;       decreaseKey(i,Integer.MIN_VALUE);       extractMin();         }
   //Function to change value at ith index and store that value at first index.   void decreaseKey(int i, int new_val)    {       harr[i] = new_val;       while (i != 0 && harr[parent(i)] > harr[i]) {           int temp = harr[i];           harr[i] = harr[parent(i)];           harr[parent(i)] = temp;           i = parent(i);       }   }
   /* You may call below MinHeapify function in     above codes. Please do not delete this code     if you are not writing your own MinHeapify */   void MinHeapify(int i) {       int l = left(i);       int r = right(i);       int smallest = i;       if (l < heap_size && harr[l] < harr[i]) smallest = l;       if (r < heap_size && harr[r] < harr[smallest]) smallest = r;       if (smallest != i) {           int temp = harr[i];           harr[i] = harr[smallest];           harr[smallest] = temp;           MinHeapify(smallest);       }   }}
 
FEAR THE PLAYERG.......!!!!!!!!!!
 
-1
chunna
This comment was deleted.
-2
singhiskingdeepankar4 months ago
Simple code C++ --
//Function to extract minimum value in heap and then to store //next minimum value at first index.int MinHeap::extractMin() {   if(heap_size==0) return -1;   if(heap_size==1)   {heap_size--; return harr[0];}   swap(harr[0], harr[heap_size-1]);   heap_size--;    MinHeapify(0);   return harr[heap_size];}
//Function to delete a key at ith index.void MinHeap::deleteKey(int i){   decreaseKey(i,INT_MIN);   extractMin();}
//Function to insert a value in Heap.void MinHeap::insertKey(int k) {   if(heap_size==capacity) return ;   heap_size++; harr[heap_size-1]=k;   for(int i=heap_size-1;i!=0 && harr[parent(i)]>harr[i];)   {       swap(harr[i],harr[parent(i)]);       i = parent(i);   }}
//Function to change value at ith index and store that value at first index.void MinHeap::decreaseKey(int i, int new_val) {   harr[i] = new_val;   while (i != 0 && harr[parent(i)] > harr[i]) {       swap(harr[i], harr[parent(i)]);       i = parent(i);   }}
/* You may call below MinHeapify function in  above codes. Please do not delete this code  if you are not writing your own MinHeapify */void MinHeap::MinHeapify(int i) {   int l = left(i);   int r = right(i);   int smallest = i;   if (l < heap_size && harr[l] < harr[i]) smallest = l;   if (r < heap_size && harr[r] < harr[smallest]) smallest = r;   if (smallest != i) {       swap(harr[i], harr[smallest]);       MinHeapify(smallest);   }}
+1
manojkanakala4444 months ago
Python code happy code :)
 
#Back-end complete function Template for Python 3 def getParent(x):  # get parent node , if exits else -1    return (x - 1) // 2 def leftChild(x):  # get left child if exists, else -1    return (2 * x + 1) if (2 * x + 1) < curr_size else -1 def rightChild(x):  # get right child if exits, else -1    return (2 * x + 2) if (2 * x + 2) < curr_size else -1 #Function to maintain the min heap property of heap. def heapify():        curr_ind = curr_size - 1    while getParent(curr_ind) != -1 and heap[getParent(curr_ind)] > heap[curr_ind]:        heap[curr_ind], heap[getParent(curr_ind)]=heap[getParent(curr_ind)],heap[curr_ind]        curr_ind = getParent(curr_ind)    return def heapifyDown(x):        # if the removed index was leaf.    if x >= curr_size:          return        if getParent(x) != -1 and heap[x] < heap[getParent(x)]:        heap[x], heap[getParent(x)] = heap[getParent(x)], heap[x]        heapifyDown(getParent(x))            if leftChild(x)==-1 or (leftChild(x)!=-1 and heap[x]<heap[leftChild(x)]):        if rightChild(x)==-1 or (rightChild(x)!=-1 and heap[x]<heap[rightChild(x)]):            return        #swapping with left child and calling function recursively for left child.    if rightChild(x)==-1:        heap[x], heap[leftChild(x)] = heap[leftChild(x)], heap[x]        heapifyDown(leftChild(x))            #swapping with right child and calling function recursively for right child.    elif leftChild(x) == -1:        heap[x], heap[rightChild(x)] = heap[rightChild(x)], heap[x]        heapifyDown(rightChild(x))            #swapping with the minimum of the two childs.        else:        if heap[rightChild(x)]<heap[leftChild(x)]:            heap[x], heap[rightChild(x)] = heap[rightChild(x)], heap[x]            heapifyDown(rightChild(x))        else:            heap[x], heap[leftChild(x)] = heap[leftChild(x)], heap[x]            heapifyDown(leftChild(x))    return #Function to insert a value in Heap. def insertKey (x):        global curr_size     #inserting value at current available index.    heap[curr_size] = x    curr_size += 1    #calling heapify function to maintain heap property.    heapify()   #Function to delete a key at ith index. def deleteKey (i):        global curr_size    if i >= curr_size:        return    #storing value of leaf node at ith index.    heap[i] = heap[curr_size - 1]    heap[curr_size - 1] = 0    curr_size -= 1       #calling heapify function to maintain heap property from index i.    heapifyDown(i) #Function to extract minimum value in heap and then to store #next minimum value at first index. def extractMin ():        if curr_size == 0:          return -1    #storing value at first index in a variable.    val = heap[0]    #deleting the value at first index.    deleteKey(0)      return val   
+1
manojkanakala4444 months ago
Java code 
class MinHeap{    int[] harr;    int capacity;    int heap_size;    int parent(int i) { return (i - 1) / 2; }    int left(int i) { return (2 * i + 1); }    int right(int i) { return (2 * i + 2); }    MinHeap(int cap) {        heap_size = 0;         capacity = cap;        harr = new int[cap];    }    //Function to insert a value in Heap.    void insertKey(int k)    {        heap_size++;        int i = heap_size - 1;        //inserting the value at leaf node.        harr[i] = k;         while (i != 0 && harr[parent(i)] > harr[i])        {            //swapping values of ith index with its parent node            //if value at parent node is greater.            int temp = harr[i];            harr[i] = harr[parent(i)];            harr[parent(i)] = temp;            i = parent(i);        }    }     //Function to change value at ith index and store that value at first index.    void decreaseKey(int i, int new_val)    {        //storing new value at ith index.        harr[i] = new_val;        while (i != 0 && harr[parent(i)] > harr[i])        {            //swapping values of ith index with its parent node            //if value at parent node is greater.          int temp = harr[i];            harr[i] = harr[parent(i)];            harr[parent(i)] = temp;            i = parent(i);        }    }       int temp = harr[i];            harr[i] = harr[parent(i)];            harr[parent(i)] = temp;            i = parent(i);        }    } 
 
0
manojkanakala4444 months ago
Any code ?
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.