The Wayback Machine - https://web.archive.org/web/20240926184537/https://www.geeksforgeeks.org/introduction-to-heap/
Open In App

Introduction to Heap

Last Updated : 28 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

What is Heap Data Structure?

A Heap is a special Tree-based Data Structure in which the tree is a complete binary tree.

Types of heaps:

Generally, heaps are of two types.

Max-Heap: 

In this heap, the value of the root node must be the greatest among all its child nodes and the same thing must be done for its left and right sub-tree also.

The total number of comparisons required in the max heap is according to the height of the tree. The height of the complete binary tree is always logn; therefore, the time complexity would also be O(logn).

Min-Heap: 

In this heap, the value of the root node must be the smallest among all its child nodes and the same thing must be done for its left and right sub-tree also.

The total number of comparisons required in the min heap is according to the height of the tree. The height of the complete binary tree is always logn; therefore, the time complexity would also be O(logn).

 

Properties of Heap:

Heap has the following Properties:

  • Complete Binary Tree: A heap tree is a complete binary tree, meaning all levels of the tree are fully filled except possibly the last level, which is filled from left to right. This property ensures that the tree is efficiently represented using an array.
  • Heap Property: This property ensures that the minimum (or maximum) element is always at the root of the tree according to the heap type.
  • Parent-Child Relationship: The relationship between a parent node at index ‘i’ and its children is given by the formulas: left child at index 2i+1 and right child at index 2i+2 for 0-based indexing of node numbers.
  • Efficient Insertion and Removal: Insertion and removal operations in heap trees are efficient. New elements are inserted at the next available position in the bottom-rightmost level, and the heap property is restored by comparing the element with its parent and swapping if necessary. Removal of the root element involves replacing it with the last element and heapifying down.
  • Efficient Access to Extremal Elements: The minimum or maximum element is always at the root of the heap, allowing constant-time access.

Operations Supported by Heap:

Operations supported by min – heap and max – heap are same. The difference is just that min-heap contains minimum element at root of the tree and max – heap contains maximum element at the root of the tree.

Heapify:

It is the process to rearrange the elements to maintain the property of heap data structure. It is done when a certain node creates an imbalance in the heap due to some operations on that node. It takes O(log N) to balance the tree. 

  • For max-heap, it balances in such a way that the maximum element is the root of that binary tree and 
  • For min-heap, it balances in such a way that the minimum element is the root of that binary tree.

Insertion:

  • If we insert a new element into the heap since we are adding a new element into the heap so it will distort the properties of the heap so we need to perform the heapify operation so that it maintains the property of the heap.

This operation also takes O(logN) time.

Examples:

Assume initially heap(taking max-heap) is as follows

           8
        /   \
     4     5
   / \
1   2

Now if we insert 10 into the heap
             8
        /      \
      4       5
   /  \      /
1    2  10 

After heapify operation final heap will be look like this
           10
         /    \
      4      8
   /  \     /
1    2  5

Deletion:

  • If we delete the element from the heap it always deletes the root element of the tree and replaces it with the last element of the tree.
  • Since we delete the root element from the heap it will distort the properties of the heap so we need to perform heapify operations so that it maintains the property of the heap. 

It takes O(logN) time.

Example:

Assume initially heap(taking max-heap) is as follows
           15
         /   \
      5     7
   /  \
2     3

Now if we delete 15 into the heap it will be replaced by leaf node of the tree for temporary.
           3
        /   \
     5     7
   /    
2

After heapify operation final heap will be look like this
           7
        /   \
     5     3
   /   
2

getMax (For max-heap) or getMin (For min-heap):

It finds the maximum element or minimum element for max-heap and min-heap respectively and as we know minimum and maximum elements will always be the root node itself for min-heap and max-heap respectively. It takes O(1) time.

removeMin or removeMax:

This operation returns and deletes the maximum element and minimum element from the max-heap and min-heap respectively. In short, it deletes the root element of the heap binary tree.

Implementation of Heap Data Structure:-

The following code shows the implementation of a max-heap.

Let’s understand the maxHeapify function in detail:-

maxHeapify is the function responsible for restoring the property of the Max Heap. It arranges the node i, and its subtrees accordingly so that the heap property is maintained.

  1. Suppose we are given an array, arr[] representing the complete binary tree. The left and the right child of ith node are in indices 2*i+1 and 2*i+2.
  2. We set the index of the current element, i, as the ‘MAXIMUM’.
  3. If arr[2 * i + 1] > arr[i], i.e., the left child is larger than the current value, it is set as ‘MAXIMUM’.
  4. Similarly if arr[2 * i + 2] > arr[i], i.e., the right child is larger than the current value, it is set as ‘MAXIMUM’.
  5. Swap the ‘MAXIMUM’ with the current element.
  6. Repeat steps 2 to 5 till the property of the heap is restored.

C++




// C++ code to depict
// the implementation of a max heap.
  
#include <bits/stdc++.h>
using namespace std;
  
// A class for Max Heap.
class MaxHeap {
    // A pointer pointing to the elements
    // in the array in the heap.
    int* arr;
  
    // Maximum possible size of
    // the Max Heap.
    int maxSize;
  
    // Number of elements in the
    // Max heap currently.
    int heapSize;
  
public:
    // Constructor function.
    MaxHeap(int maxSize);
  
    // Heapifies a sub-tree taking the
    // given index as the root.
    void MaxHeapify(int);
  
    // Returns the index of the parent
    // of the element at ith index.
    int parent(int i)
    {
        return (i - 1) / 2;
    }
  
    // Returns the index of the left child.
    int lChild(int i)
    {
        return (2 * i + 1);
    }
  
    // Returns the index of the
    // right child.
    int rChild(int i)
    {
        return (2 * i + 2);
    }
  
    // Removes the root which in this
    // case contains the maximum element.
    int removeMax();
  
    // Increases the value of the key
    // given by index i to some new value.
    void increaseKey(int i, int newVal);
  
    // Returns the maximum key
    // (key at root) from max heap.
    int getMax()
    {
        return arr[0];
    }
  
    int curSize()
    {
        return heapSize;
    }
  
    // Deletes a key at given index i.
    void deleteKey(int i);
  
    // Inserts a new key 'x' in the Max Heap.
    void insertKey(int x);
};
  
// Constructor function builds a heap
// from a given array a[]
// of the specified size.
MaxHeap::MaxHeap(int totSize)
{
    heapSize = 0;
    maxSize = totSize;
    arr = new int[totSize];
}
  
// Inserting a new key 'x'.
void MaxHeap::insertKey(int x)
{
    // To check whether the key
    // can be inserted or not.
    if (heapSize == maxSize) {
        cout << "\nOverflow: Could not insertKey\n";
        return;
    }
  
    // The new key is initially
    // inserted at the end.
    heapSize++;
    int i = heapSize - 1;
    arr[i] = x;
  
    // The max heap property is checked
    // and if violation occurs,
    // it is restored.
    while (i != 0 && arr[parent(i)] < arr[i]) {
        swap(arr[i], arr[parent(i)]);
        i = parent(i);
    }
}
  
// Increases value of key at
// index 'i' to new_val.
void MaxHeap::increaseKey(int i, int newVal)
{
    arr[i] = newVal;
    while (i != 0 && arr[parent(i)] < arr[i]) {
        swap(arr[i], arr[parent(i)]);
        i = parent(i);
    }
}
  
// To remove the root node which contains
// the maximum element of the Max Heap.
int MaxHeap::removeMax()
{
    // Checking whether the heap array
    // is empty or not.
    if (heapSize <= 0)
        return INT_MIN;
    if (heapSize == 1) {
        heapSize--;
        return arr[0];
    }
  
    // Storing the maximum element
    // to remove it.
    int root = arr[0];
    arr[0] = arr[heapSize - 1];
    heapSize--;
  
    // To restore the property
    // of the Max heap.
    MaxHeapify(0);
  
    return root;
}
  
// In order to delete a key
// at a given index i.
void MaxHeap::deleteKey(int i)
{
    // It increases the value of the key
    // to infinity and then removes
    // the maximum value.
    increaseKey(i, INT_MAX);
    removeMax();
}
  
// To heapify the subtree this method
// is called recursively
void MaxHeap::MaxHeapify(int i)
{
    int l = lChild(i);
    int r = rChild(i);
    int largest = i;
    if (l < heapSize && arr[l] > arr[i])
        largest = l;
    if (r < heapSize && arr[r] > arr[largest])
        largest = r;
    if (largest != i) {
        swap(arr[i], arr[largest]);
        MaxHeapify(largest);
    }
}
  
// Driver program to test above functions.
int main()
{
    // Assuming the maximum size of the heap to be 15.
    MaxHeap h(15);
  
    // Asking the user to input the keys:
    int k, i, n = 6, arr[10];
    cout << "Entered 6 keys:- 3, 10, 12, 8, 2, 14 \n";
    h.insertKey(3);
    h.insertKey(10);
    h.insertKey(12);
    h.insertKey(8);
    h.insertKey(2);
    h.insertKey(14);
  
    // Printing the current size
    // of the heap.
    cout << "The current size of the heap is "
         << h.curSize() << "\n";
  
    // Printing the root element which is
    // actually the maximum element.
    cout << "The current maximum element is " << h.getMax()
         << "\n";
  
    // Deleting key at index 2.
    h.deleteKey(2);
  
    // Printing the size of the heap
    // after deletion.
    cout << "The current size of the heap is "
         << h.curSize() << "\n";
  
    // Inserting 2 new keys into the heap.
    h.insertKey(15);
    h.insertKey(5);
    cout << "The current size of the heap is "
         << h.curSize() << "\n";
    cout << "The current maximum element is " << h.getMax()
         << "\n";
  
    return 0;
}


Java




// Java code to depict
// the implementation of a max heap.
import java.util.Arrays;
import java.util.Scanner;
  
public class MaxHeap {
    // A pointer pointing to the elements
    // in the array in the heap.
    int[] arr;
  
    // Maximum possible size of
    // the Max Heap.
    int maxSize;
  
    // Number of elements in the
    // Max heap currently.
    int heapSize;
  
    // Constructor function.
    MaxHeap(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        heapSize = 0;
    }
  
    // Heapifies a sub-tree taking the
    // given index as the root.
    void MaxHeapify(int i) {
        int l = lChild(i);
        int r = rChild(i);
        int largest = i;
        if (l < heapSize && arr[l] > arr[i])
            largest = l;
        if (r < heapSize && arr[r] > arr[largest])
            largest = r;
        if (largest != i) {
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;
            MaxHeapify(largest);
        }
    }
  
    // Returns the index of the parent
    // of the element at ith index.
    int parent(int i) {
        return (i - 1) / 2;
    }
  
    // Returns the index of the left child.
    int lChild(int i) {
        return (2 * i + 1);
    }
  
    // Returns the index of the
    // right child.
    int rChild(int i) {
        return (2 * i + 2);
    }
  
    // Removes the root which in this
    // case contains the maximum element.
    int removeMax() {
        // Checking whether the heap array
        // is empty or not.
        if (heapSize <= 0)
            return Integer.MIN_VALUE;
        if (heapSize == 1) {
            heapSize--;
            return arr[0];
        }
  
        // Storing the maximum element
        // to remove it.
        int root = arr[0];
        arr[0] = arr[heapSize - 1];
        heapSize--;
  
        // To restore the property
        // of the Max heap.
        MaxHeapify(0);
  
        return root;
    }
  
    // Increases value of key at
    // index 'i' to new_val.
    void increaseKey(int i, int newVal) {
        arr[i] = newVal;
        while (i != 0 && arr[parent(i)] < arr[i]) {
            int temp = arr[i];
            arr[i] = arr[parent(i)];
            arr[parent(i)] = temp;
            i = parent(i);
        }
    }
  
    // Returns the maximum key
    // (key at root) from max heap.
    int getMax() {
        return arr[0];
    }
  
    int curSize() {
        return heapSize;
    }
  
    // Deletes a key at given index i.
    void deleteKey(int i) {
        // It increases the value of the key
        // to infinity and then removes
        // the maximum value.
        increaseKey(i, Integer.MAX_VALUE);
        removeMax();
    }
  
    // Inserts a new key 'x' in the Max Heap.
    void insertKey(int x) {
        // To check whether the key
        // can be inserted or not.
        if (heapSize == maxSize) {
            System.out.println("\nOverflow: Could not insertKey\n");
            return;
        }
  
        // The new key is initially
        // inserted at the end.
        heapSize++;
        int i = heapSize - 1;
        arr[i] = x;
  
        // The max heap property is checked
        // and if violation occurs,
        // it is restored.
        while (i != 0 && arr[parent(i)] < arr[i]) {
            int temp = arr[i];
            arr[i] = arr[parent(i)];
            arr[parent(i)] = temp;
            i = parent(i);
        }
    }
  
    // Driver program to test above functions.
    public static void main(String[] args) {
        // Assuming the maximum size of the heap to be 15.
        MaxHeap h = new MaxHeap(15);
  
        // Asking the user to input the keys:
        int k, i, n = 6;
        System.out.println("Entered 6 keys:- 3, 10, 12, 8, 2, 14 \n");
        h.insertKey(3);
        h.insertKey(10);
        h.insertKey(12);
        h.insertKey(8);
        h.insertKey(2);
        h.insertKey(14);
  
        // Printing the current size
        // of the heap.
        System.out.println("The current size of the heap is "
                + h.curSize() + "\n");
  
        // Printing the root element which is
        // actually the maximum element.
        System.out.println("The current maximum element is " + h.getMax()
                + "\n");
  
        // Deleting key at index 2.
        h.deleteKey(2);
  
        // Printing the size of the heap
        // after deletion.
        System.out.println("The current size of the heap is "
                + h.curSize() + "\n");
  
        // Inserting 2 new keys into the heap.
        h.insertKey(15);
        h.insertKey(5);
        System.out.println("The current size of the heap is "
                + h.curSize() + "\n");
        System.out.println("The current maximum element is " + h.getMax()
                + "\n");
    }
}


Python3




# Python code to depict
# the implementation of a max heap.
  
class MaxHeap:
    # A pointer pointing to the elements
    # in the array in the heap.
    arr = []
  
    # Maximum possible size of
    # the Max Heap.
    maxSize = 0
  
    # Number of elements in the
    # Max heap currently.
    heapSize = 0
  
    # Constructor function.
    def __init__(self, maxSize):
        self.maxSize = maxSize
        self.arr = [None]*maxSize
        self.heapSize = 0
  
    # Heapifies a sub-tree taking the
    # given index as the root.
    def MaxHeapify(self, i):
        l = self.lChild(i)
        r = self.rChild(i)
        largest = i
        if l < self.heapSize and self.arr[l] > self.arr[i]:
            largest = l
        if r < self.heapSize and self.arr[r] > self.arr[largest]:
            largest = r
        if largest != i:
            temp = self.arr[i]
            self.arr[i] = self.arr[largest]
            self.arr[largest] = temp
            self.MaxHeapify(largest)
  
    # Returns the index of the parent
    # of the element at ith index.
    def parent(self, i):
        return (i - 1) // 2
  
    # Returns the index of the left child.
    def lChild(self, i):
        return (2 * i + 1)
  
    # Returns the index of the
    # right child.
    def rChild(self, i):
        return (2 * i + 2)
  
    # Removes the root which in this
    # case contains the maximum element.
    def removeMax(self):
        # Checking whether the heap array
        # is empty or not.
        if self.heapSize <= 0:
            return None
        if self.heapSize == 1:
            self.heapSize -= 1
            return self.arr[0]
  
        # Storing the maximum element
        # to remove it.
        root = self.arr[0]
        self.arr[0] = self.arr[self.heapSize - 1]
        self.heapSize -= 1
  
        # To restore the property
        # of the Max heap.
        self.MaxHeapify(0)
  
        return root
  
    # Increases value of key at
    # index 'i' to new_val.
    def increaseKey(self, i, newVal):
        self.arr[i] = newVal
        while i != 0 and self.arr[self.parent(i)] < self.arr[i]:
            temp = self.arr[i]
            self.arr[i] = self.arr[self.parent(i)]
            self.arr[self.parent(i)] = temp
            i = self.parent(i)
  
    # Returns the maximum key
    # (key at root) from max heap.
    def getMax(self):
        return self.arr[0]
  
    def curSize(self):
        return self.heapSize
  
    # Deletes a key at given index i.
    def deleteKey(self, i):
        # It increases the value of the key
        # to infinity and then removes
        # the maximum value.
        self.increaseKey(i, float("inf"))
        self.removeMax()
  
    # Inserts a new key 'x' in the Max Heap.
    def insertKey(self, x):
        # To check whether the key
        # can be inserted or not.
        if self.heapSize == self.maxSize:
            print("\nOverflow: Could not insertKey\n")
            return
  
        # The new key is initially
        # inserted at the end.
        self.heapSize += 1
        i = self.heapSize - 1
        self.arr[i] = x
  
        # The max heap property is checked
        # and if violation occurs,
        # it is restored.
        while i != 0 and self.arr[self.parent(i)] < self.arr[i]:
            temp = self.arr[i]
            self.arr[i] = self.arr[self.parent(i)]
            self.arr[self.parent(i)] = temp
            i = self.parent(i)
  
  
# Driver program to test above functions.
if __name__ == '__main__':
    # Assuming the maximum size of the heap to be 15.
    h = MaxHeap(15)
  
    # Asking the user to input the keys:
    k, i, n = 6, 0, 6
    print("Entered 6 keys:- 3, 10, 12, 8, 2, 14 \n")
    h.insertKey(3)
    h.insertKey(10)
    h.insertKey(12)
    h.insertKey(8)
    h.insertKey(2)
    h.insertKey(14)
  
    # Printing the current size
    # of the heap.
    print("The current size of the heap is "
          + str(h.curSize()) + "\n")
  
    # Printing the root element which is
    # actually the maximum element.
    print("The current maximum element is " + str(h.getMax())
          + "\n")
  
    # Deleting key at index 2.
    h.deleteKey(2)
  
    # Printing the size of the heap
    # after deletion.
    print("The current size of the heap is "
          + str(h.curSize()) + "\n")
  
    # Inserting 2 new keys into the heap.
    h.insertKey(15)
    h.insertKey(5)
    print("The current size of the heap is "
          + str(h.curSize()) + "\n")
    print("The current maximum element is " + str(h.getMax())
          + "\n")


Javascript




// JavaScript code to depict
// the implementation of a max heap.
  
class MaxHeap {
    constructor(maxSize) {
        // the array in the heap.
        this.arr = new Array(maxSize).fill(null);
  
        // Maximum possible size of
        // the Max Heap.
        this.maxSize = maxSize;
  
        // Number of elements in the
        // Max heap currently.
        this.heapSize = 0;
    }
  
    // Heapifies a sub-tree taking the
    // given index as the root.
    MaxHeapify(i) {
        const l = this.lChild(i);
        const r = this.rChild(i);
        let largest = i;
        if (l < this.heapSize && this.arr[l] > this.arr[i]) {
            largest = l;
        }
        if (r < this.heapSize && this.arr[r] > this.arr[largest]) {
            largest = r;
        }
        if (largest !== i) {
            const temp = this.arr[i];
            this.arr[i] = this.arr[largest];
            this.arr[largest] = temp;
            this.MaxHeapify(largest);
        }
    }
  
    // Returns the index of the parent
    // of the element at ith index.
    parent(i) {
        return Math.floor((i - 1) / 2);
    }
  
    // Returns the index of the left child.
    lChild(i) {
        return 2 * i + 1;
    }
  
    // Returns the index of the
    // right child.
    rChild(i) {
        return 2 * i + 2;
    }
  
    // Removes the root which in this
    // case contains the maximum element.
    removeMax() {
        // Checking whether the heap array
        // is empty or not.
        if (this.heapSize <= 0) {
            return null;
        }
        if (this.heapSize === 1) {
            this.heapSize -= 1;
            return this.arr[0];
        }
  
        // Storing the maximum element
        // to remove it.
        const root = this.arr[0];
        this.arr[0] = this.arr[this.heapSize - 1];
        this.heapSize -= 1;
  
        // To restore the property
        // of the Max heap.
        this.MaxHeapify(0);
  
        return root;
    }
  
    // Increases value of key at
    // index 'i' to new_val.
    increaseKey(i, newVal) {
        this.arr[i] = newVal;
        while (i !== 0 && this.arr[this.parent(i)] < this.arr[i]) {
            const temp = this.arr[i];
            this.arr[i] = this.arr[this.parent(i)];
            this.arr[this.parent(i)] = temp;
            i = this.parent(i);
        }
    }
  
    // Returns the maximum key
    // (key at root) from max heap.
    getMax() {
        return this.arr[0];
    }
  
    curSize() {
        return this.heapSize;
    }
  
    // Deletes a key at given index i.
    deleteKey(i) {
        // It increases the value of the key
        // to infinity and then removes
        // the maximum value.
        this.increaseKey(i, Infinity);
        this.removeMax();
    }
  
    // Inserts a new key 'x' in the Max Heap.
    insertKey(x) {
        // To check whether the key
        // can be inserted or not.
        if (this.heapSize === this.maxSize) {
            console.log("\nOverflow: Could not insertKey\n");
            return;
        }
  
        let i = this.heapSize;
        this.arr[i] = x;
  
        // The new key is initially
        // inserted at the end.
        this.heapSize += 1;
  
  
  
        // The max heap property is checked
        // and if violation occurs,
        // it is restored.
        while (i !== 0 && this.arr[this.parent(i)] < this.arr[i]) {
            const temp = this.arr[i];
            this.arr[i] = this.arr[this.parent(i)];
            this.arr[this.parent(i)] = temp;
            i = this.parent(i);
        }
    }
}
  
  
// Driver program to test above functions.
  
// Assuming the maximum size of the heap to be 15.
const h = new MaxHeap(15);
  
// Asking the user to input the keys:
console.log("Entered 6 keys:- 3, 10, 12, 8, 2, 14 \n");
  
h.insertKey(3);
h.insertKey(10);
h.insertKey(12);
h.insertKey(8);
h.insertKey(2);
h.insertKey(14);
  
  
// Printing the current size
// of the heap.
console.log(
    "The current size of the heap is " + h.curSize() + "\n"
);
  
  
// Printing the root element which is
// actually the maximum element.
console.log(
    "The current maximum element is " + h.getMax() + "\n"
);
  
  
// Deleting key at index 2.
h.deleteKey(2);
  
  
// Printing the size of the heap
// after deletion.
console.log(
    "The current size of the heap is " + h.curSize() + "\n"
);
  
  
// Inserting 2 new keys into the heap.
h.insertKey(15);
h.insertKey(5);
  
console.log(
    "The current size of the heap is " + h.curSize() + "\n"
);
  
console.log(
    "The current maximum element is " + h.getMax() + "\n"
);
  
// Contributed by sdeadityasharma


Output

Entered 6 keys:- 3, 10, 12, 8, 2, 14 
The current size of the heap is 6
The current maximum element is 14
The current size of the heap is 5
The current size of the heap is 7
The current maximum element is 15

Applications of Heap Data Structure:

  • Priority Queues: Priority queues can be efficiently implemented using Binary Heap because it supports insert(), delete() and extractmax(), decreaseKey() operations in O(log N) time. 
  • Binomial Heap and Fibonacci Heap are variations of Binary Heap. These variations perform union also in O(log N) time which is an O(N) operation in Binary Heap.
  • Order statistics: The Heap data structure can be used to efficiently find the kth smallest (or largest) element in an array. You can see this gfg article to know more about the kth smallest or largest element.

Advantages of Heaps:

  • Fast access to maximum/minimum element (O(1))
  • Efficient Insertion and Deletion operations (O(log n))
    Flexible size
  • Can be efficiently implemented as an array
  • Suitable for real-time applications

Disadvantages of Heaps:

  • Not suitable for searching for an element other than maximum/minimum (O(n) in worst case)
  • Extra memory overhead to maintain heap structure
  • Slower than other data structures like arrays and linked lists for non-priority queue operations.


Previous Article
Next Article

Similar Reads

Difference between Binary Heap, Binomial Heap and Fibonacci Heap
Binary Heap:A Binary Heap is a Binary Tree with following properties. It’s a complete binary tree i.e., 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.A Binary Heap is either Min Heap or Max Heap. In a Min
2 min read
Convert Min Heap to Max Heap
Given an array representation of min Heap, convert it to max Heap. Examples: 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} 20 / \ 18 10 / \ / \ 12 9 9 3 / \ /5 6 8 Input: arr[] = {3, 4, 8, 11, 13}Output: arr[] = {13, 11, 8, 4, 3} Approach: To solve the p
10 min read
Heap Sort for decreasing order using min heap
Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1} Output : arr[] = {10, 5, 3, 1} Input : arr[] = {1, 50, 100, 25} Output : arr[] = {100, 50, 25, 1} Prerequisite: Heap sort using min heap. Algorithm : Build a min heap from the input data. At this point, the smallest item is stored
13 min read
When building a Heap, is the structure of Heap unique?
What is Heap? A heap is a tree based data structure where the tree is a complete binary tree that maintains the property that either the children of a node are less than itself (max heap) or the children are greater than the node (min heap). Properties of Heap: Structural Property: This property states that it should be A Complete Binary Tree. For
4 min read
Difference between Min Heap and Max Heap
A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Since a heap is a complete binary tree, a heap with N nodes has log N height. It is useful to remove the highest or lowest priority element. It is typically represented as an array. There are two types of Heaps in the data structure. Min-HeapIn a Min-Heap the
3 min read
What's the relationship between "a" heap and "the" heap?
A Heap: "A Heap" refers to the heap data structure where we can store data in a specific order. Heap is a Tree-based data structure where the tree is a complete binary tree. Heap is basically of two types: Max-Heap: The key at the Root node of the tree will be the greatest among all the keys present in that heap and the same property will be follow
15+ min read
Introduction to Min-Heap Data Structure
A Min-Heap is defined as a type of Heap Data Structure in which each node is smaller than or equal to its children.  The heap data structure is a type of binary tree that is commonly used in computer science for various purposes, including sorting, searching, and organizing data. Purpose and Use Cases of Min-Heap: Implementing Priority Queue: One o
15+ min read
Fibonacci Heap | Set 1 (Introduction)
INTRODUCTION:A Fibonacci heap is a data structure used for implementing priority queues. It is a type of heap data structure, but with several improvements over the traditional binary heap and binomial heap data structures.The key advantage of a Fibonacci heap over other heap data structures is its fast amortized running time for operations such as
5 min read
Data Structures | Heap | Question 2
A max-heap is a heap where the value of each parent is greater than or equal to the values of its children. Which of the following is a max-heap? (GATE CS 2011) . (A) A (B) B (C) C (D) D Answer: (B) Explanation: (A) The provided tree is not a complete tree. (B) The tree is a max-heap, as the root element is greater than all of its children elements
1 min read
Data Structures | Heap | Question 5
Consider a binary max-heap implemented using an array. Which among the following arrays represents a binary max-heap? (More than one option correct) (A) 25,12,16,8,10,13,14 (B) 25,12,16,13,10,8,14 (C) 25,14,16,13,10,8,12 (D) 25,14,12,13,10,8,16 Answer: (A) (C) Explanation: A tree is max-heap if data at every node in the tree is greater than or equa
1 min read
Data Structures | Heap | Question 6
A min- Heap is a complete binary tree. (A) True (B) False Answer: (A) Explanation: A max-heap is a special Tree-based data structure in which the tree is a complete binary tree. A complete binary tree is a special type of binary tree where all the levels of the tree are filled completely except the lowest level nodes which are filled from as left a
1 min read
Data Structures | Heap | Question 7
We have a binary heap on n elements and wish to insert n more elements (not necessarily one after another) into this heap. The total time required for this is (A) theta(logn) (B) theta(n) (C) theta(nlogn) (D) theta(n^2) (A) A (B) B (C) C (D) D Answer: (B) Explanation: We can reduce the problem to build heap for 2n elements. Time taken for build hea
1 min read
Data Structures | Heap | Question 11
Given two max heaps of size n each, what is the minimum possible time complexity to make a one max-heap of size from elements of two max heaps? (A) O(n^2) (B) O(nLogLogn) (C) O(n) (D) O(nLogn) Answer: (C) Explanation: We can build a heap of 2n elements in O(n) time. Following are the steps. Create an array of size 2n and copy elements of both heaps
1 min read
Number of ways to form a heap with n distinct integers
Given n, how many distinct Max Heap can be made from n distinct integers? Examples: Input : n = 3 Output : Assume the integers are 1, 2, 3. Then the 2 possible max heaps are: 3 / \ 1 2 3 / \ 2 1 Input : n = 4 Output : Assume the integers are 1, 2, 3, 4. Then the 3 possible max heaps are: 4 / \ 3 2 / 1 4 / \ 2 3 / 1 4 / \ 3 1 / 2 Since there is only
13 min read
Skew Heap
A skew heap (or self - adjusting heap) is a heap data structure implemented as a binary tree. Skew heaps are advantageous because of their ability to merge more quickly than binary heaps. In contrast with binary heaps, there are no structural constraints, so there is no guarantee that the height of the tree is logarithmic. Only two conditions must
10 min read
Convert BST to Max Heap
Given a Binary Search Tree which is also a Complete Binary Tree. The problem is to convert a given BST into a Special Max Heap with the condition that all the values in the left subtree of a node should be less than all the values in the right subtree of the node. This condition is applied to all the nodes in the so-converted Max Heap. Examples: In
15+ min read
Top 50 Problems on Heap Data Structure asked in SDE Interviews
A Heap is a special Tree-based Data Structure in which the tree is a complete binary tree. Generally, heaps are of two types: Max-Heap and Min-Heap. To know more about this Data Structure in-depth refer to the Tutorial on Heap Data-Structure. Given below are the most frequently asked interview questions on Heaps:  Easy Interview Questions on Heap D
2 min read
Python Code for time Complexity plot of Heap Sort
Prerequisite : HeapSort Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. We implement Heap Sort here, call it for different sized random lists, meas
3 min read
Minimum element in a max heap
Given a max heap, find the minimum element present in the heap. Examples: Input : 100 / \ 75 50 / \ / \ 55 10 2 40 Output : 2 Input : 20 / \ 4 18 Output : 4 Brute force approach: We can check all the nodes in the max heap to get the minimum element. Note that this approach works on any binary tree and does not makes use of any property of the max h
9 min read
Maximum element in min heap
Given a min heap, find the maximum element present in the heap. Examples: Input : 10 / \ 25 23 / \ / \ 45 30 50 40 Output : 50 Input : 20 / \ 40 28 Output : 40 Brute force approach: We can check all the nodes in the min-heap to get the maximum element. Note that this approach works on any binary tree and does not makes use of any property of the mi
8 min read
Fibonacci Heap - Insertion and Union
Fibonacci Heap is a collection of trees with min-heap or max-heap property. In Fibonacci Heap, trees can have any shape even all trees can be single nodes (This is unlike Binomial Heap where every tree has to be a Binomial Tree). In this article, we will discuss Insertion and Union operation on Fibonacci Heap. Prerequisites: Fibonacci Heap (Introdu
7 min read
Fibonacci Heap - Deletion, Extract min and Decrease key
In the last post, we discussed the Insertion and Union of Fibonacci Heaps. In this post, we will discuss Extract_min(), Decrease_key() and Deletion() operations on Fibonacci heap. Prerequisites: Fibonacci Heap (Introduction) Fibonacci Heap - Insertion and Union Extract_min(): We create a function for deleting the minimum node and setting the min po
12 min read
Memory representation of Binomial Heap
Prerequisites: Binomial Heap Binomial trees are multi-way trees typically stored in the left-child, right-sibling representation, and each node stores its degree. Binomial heaps are collection of binomial trees stored in ascending order of size. The root list in the heap is a linked list of roots of the Binomial heap. The degree of the nodes of the
2 min read
Max Heap in Java
A max-heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored an index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2. Illustration: Max Heap How is M
6 min read
Building Heap from Array
Given an array of N elements. The task is to build a Binary Heap from the given array. The heap can be either Max Heap or Min Heap. Examples: Input: arr[] = {4, 10, 3, 5, 1}Output: Corresponding Max-Heap: 10 / \ 5 3 / \4 1 Input: arr[] = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17}Output: Corresponding Max-Heap: 17 / \ 15 13 / \ / \ 9 6 5 10 / \ / \ 4 8 3
14 min read
Maximise the number of toys that can be purchased with amount K using min Heap
Given an array arr[] consisting of the cost of toys and an integer K depicting the amount of money available to purchase toys. The task is to find the maximum number of toys one can buy with the amount K.Note: One can buy only 1 quantity of a particular toy. Examples: Input: arr[] = {1, 12, 5, 111, 200, 1000, 10, 9, 12, 15}, K = 50 Output: 6 Toys w
5 min read
Min Heap in Python
A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored at index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2 for 0 based indexing and for 1 b
5 min read
Max Heap in Python
A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored a index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2. Examples of Max Heap : How is Ma
7 min read
Min Heap meaning in DSA
A min heap is a binary tree-based data structure where the value of each node is less than or equal to its child nodes. In other words, the root node is always the minimum element in the heap. Here is an example of the min heap tree: Characteristics of Min Heap :A min heap is a complete binary tree. This property ensures that the tree is balanced a
3 min read
Weak Heap
It is a binary tree that has following properties:- (1) Every key in the right sub-tree of a node is greater than the key stored in the node itself, (2) The root has no left child, and (3) Leaves are only found on the last two levels of the tree. It is used for implementing priority queues. The reason why a user might prefer a weak heap over a bina
7 min read
Article Tags :
Practice Tags :