Min Heap Implementation

About

A Min Heap is a binary heap where the parent node is always smaller than its children. The smallest element is stored at the root.

Operations Supported:

  • Insert (O(log n)) → Add an element while maintaining heap order.

When we insert into a min-heap, we always start by inserting the element at the bottom. We insert at the rightmost spot so as to maintain the complete tree property. Then, we fix the tree by swapping the new element with its parent, until we find an appropriate spot for the element. We essentially bubble up the minimum element.

  • Extract Min (O(log n)) → Remove the smallest element.

Removes and returns the smallest element (root) while maintaining heap order.

  • The root node (minimum element) is removed.

  • The last element in the heap is moved to the root to maintain the complete tree property.

  • Then, the heap is restructured by bubbling down (heapify down) the new root to restore the heap property.

  • We compare the new root with its smallest child and swap if necessary, repeating this process until the correct position is found.

  • Peek Min (O(1)) → Get the smallest element without removing it.

Retrieves the minimum element without removing it.

  • Since the smallest element is always at the root in a Min Heap, we simply return the root value.

  • This operation is constant time O(1) because no restructuring is needed.

  • Heapify (O(log n)) → Maintain heap property after insertion or deletion.

Ensures the heap property is maintained after insertion or deletion.

  • Heapify Up: Used after insertion to bubble up the inserted element.

  • Heapify Down: Used after deletion (Extract Min) to bubble down the root.

  • Each step reduces the number of swaps exponentially, leading to O(log n) complexity.

Min Heap Implementation in Java

Time Complexity

Operation
Time Complexity

Insert

O(log n)

Extract Min

O(log n)

Peek Min

O(1)

Heapify

O(log n)

Last updated