LeetCode Grinding
Data Structures2 min read

Understanding Priority Queue (Min-Heap)

Build a min heap and use it to insert items and remove the smallest item by priority.

In this article 5 sections

I had used priority queues before implementing one. Building this min heap helped me follow what happens when an insertion or removal breaks the ordering between a parent and its children.

What Is a Min Heap?

A min heap is a binary tree where:

  • The parent is always smaller than or equal to its children
  • The root is the smallest element
  • It is a complete binary tree (filled left to right)

This structure lets me get the minimum element in O(1) and remove it in O(log n).

My Min Heap Implementation

The array stores the tree from left to right, one level at a time. The index calculations below find a node's parent and children.

javascript
class MinHeap {
    constructor() {
        this.heap = [];
    }

    // Helper methods to navigate the tree
    getParentIndex(i) { 
        return Math.floor((i - 1) / 2); 
    }
    
    getLeftChildIndex(i) { 
        return 2 * i + 1; 
    }
    
    getRightChildIndex(i) { 
        return 2 * i + 2; 
    }

    // Add element to heap
    add(value) {
        this.heap.push(value);
        this.heapifyUp(); // Maintain heap property
    }

    // Remove and return minimum element
    poll() {
        if (this.heap.length === 0) return null;
        if (this.heap.length === 1) {
            return this.heap.pop();
        }

        const root = this.heap[0];
        this.heap[0] = this.heap.pop(); // Move last element to root
        this.heapifyDown(); // Maintain heap property
        return root;
    }

    // Move element up to maintain heap property
    heapifyUp() {
        let index = this.heap.length - 1;
        
        while (index > 0) {
            const parentIndex = this.getParentIndex(index);
            
            // If parent is smaller or equal, we're done
            if (this.heap[parentIndex] <= this.heap[index]) {
                break;
            }
            
            // Swap with parent
            [this.heap[index], this.heap[parentIndex]] = 
            [this.heap[parentIndex], this.heap[index]];
            index = parentIndex;
        }
    }

    // Move element down to maintain heap property
    heapifyDown() {
        let index = 0;
        
        while (this.getLeftChildIndex(index) < this.heap.length) {
            const leftIndex = this.getLeftChildIndex(index);
            const rightIndex = this.getRightChildIndex(index);
            let smallerChildIndex = leftIndex;

            // Find smaller child
            if (rightIndex < this.heap.length && 
                this.heap[rightIndex] < this.heap[leftIndex]) {
                smallerChildIndex = rightIndex;
            }

            // If current is smaller than both children, we're done
            if (this.heap[index] <= this.heap[smallerChildIndex]) {
                break;
            }

            // Swap with smaller child
            [this.heap[index], this.heap[smallerChildIndex]] = 
            [this.heap[smallerChildIndex], this.heap[index]];
            index = smallerChildIndex;
        }
    }

    isEmpty() {
        return this.heap.length === 0;
    }
}

How It Works

Adding an element:

  1. Add to the end of the array
  2. "Bubble up" by comparing with parent
  3. Swap if parent is larger
  4. Repeat until heap property is restored

Removing minimum:

  1. Remove root (minimum)
  2. Move last element to root
  3. "Bubble down" by comparing with children
  4. Swap with smaller child if needed
  5. Repeat until heap property is restored
javascript
const minHeap = new MinHeap();
minHeap.add(10);
minHeap.add(5);
minHeap.add(20);
minHeap.add(1);

while (!minHeap.isEmpty()) {
    console.log(minHeap.poll()); // Prints: 1, 5, 10, 20
}

Java's Built in PriorityQueue

In Java, I can use the built in PriorityQueue, which is a min heap by default:

java
import java.util.PriorityQueue;

public class MinHeapExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        
        minHeap.add(10);
        minHeap.add(5);
        minHeap.add(20);
        minHeap.add(1);
        
        while (!minHeap.isEmpty()) {
            System.out.println(minHeap.poll()); // Prints: 1, 5, 10, 20
        }
    }
}

Cost of repairing the heap

An insertion can move from the last level to the root. A removal can move from the root to the last level. A complete binary tree has O(log n) levels, so each repair takes O(log n) time. The array uses O(n) space.

Reading the minimum only needs the root, so it takes O(1) time. The rest of the array is not fully sorted; only the ordering between each parent and its children is guaranteed.

Filed under

Thanks for reading

What do you think?

Leave a reaction or a comment below.

Loading reactions…

Share this post

Loading comments...

Related posts

All writing