Library

Volume 3 · Coding Problems & Data Structures

Notebook
Sign in

Section 21

Min-Heap / Priority Queue (Full Working Code)

795 words · about 4 min

Concept: A complete binary tree, array-backed, where every parent ≤ its children. Supports O(log n) insert/extract-min and O(1) peek.

Python Implementation

class MinHeap:
    """
    Array-backed binary min-heap.
    For index i: parent = (i-1)//2, left = 2i+1, right = 2i+2
    """

    def __init__(self):
        self.heap = []

    def push(self, value) -> None:
        self.heap.append(value)
        self._sift_up(len(self.heap) - 1)

    def pop(self):
        if not self.heap:
            raise IndexError("pop from empty heap")
        if len(self.heap) == 1:
            return self.heap.pop()

        min_val = self.heap[0]
        self.heap[0] = self.heap.pop()
        self._sift_down(0)
        return min_val

    def peek(self):
        if not self.heap:
            raise IndexError("peek from empty heap")
        return self.heap[0]

    def _sift_up(self, index: int) -> None:
        while index > 0:
            parent = (index - 1) // 2
            if self.heap[index] < self.heap[parent]:
                self.heap[index], self.heap[parent] = self.heap[parent], self.heap[index]
                index = parent
            else:
                break

    def _sift_down(self, index: int) -> None:
        size = len(self.heap)
        while True:
            smallest = index
            left, right = 2 * index + 1, 2 * index + 2
            if left < size and self.heap[left] < self.heap[smallest]:
                smallest = left
            if right < size and self.heap[right] < self.heap[smallest]:
                smallest = right
            if smallest != index:
                self.heap[index], self.heap[smallest] = self.heap[smallest], self.heap[index]
                index = smallest
            else:
                break

    def __len__(self):
        return len(self.heap)


# --- Usage: Top-K Frequent Elements ---
def top_k_frequent(nums: list[int], k: int) -> list[int]:
    from collections import Counter
    count = Counter(nums)
    heap = MinHeap()
    for num, freq in count.items():
        heap.push((freq, num))
        if len(heap) > k:
            heap.pop()
    return [heap.pop()[1] for _ in range(len(heap))]

print(top_k_frequent([1, 1, 1, 2, 2, 3], 2))  # [2, 1]

C# Implementation

using System;
using System.Collections.Generic;

public class MinHeap<T> where T : IComparable<T>
{
    private readonly List<T> _heap = new();

    public int Count => _heap.Count;

    public void Push(T value)
    {
        _heap.Add(value);
        SiftUp(_heap.Count - 1);
    }

    public T Pop()
    {
        if (_heap.Count == 0) throw new InvalidOperationException("Heap is empty");
        var min = _heap[0];
        var last = _heap[^1];
        _heap.RemoveAt(_heap.Count - 1);

        if (_heap.Count > 0)
        {
            _heap[0] = last;
            SiftDown(0);
        }
        return min;
    }

    public T Peek()
    {
        if (_heap.Count == 0) throw new InvalidOperationException("Heap is empty");
        return _heap[0];
    }

    private void SiftUp(int index)
    {
        while (index > 0)
        {
            int parent = (index - 1) / 2;
            if (_heap[index].CompareTo(_heap[parent]) < 0)
            {
                (_heap[index], _heap[parent]) = (_heap[parent], _heap[index]);
                index = parent;
            }
            else break;
        }
    }

    private void SiftDown(int index)
    {
        int size = _heap.Count;
        while (true)
        {
            int smallest = index, left = 2 * index + 1, right = 2 * index + 2;
            if (left < size && _heap[left].CompareTo(_heap[smallest]) < 0) smallest = left;
            if (right < size && _heap[right].CompareTo(_heap[smallest]) < 0) smallest = right;
            if (smallest != index)
            {
                (_heap[index], _heap[smallest]) = (_heap[smallest], _heap[index]);
                index = smallest;
            }
            else break;
        }
    }
}

// --- Usage: Top-K Frequent Elements ---
public static List<int> TopKFrequent(int[] nums, int k)
{
    var counts = new Dictionary<int, int>();
    foreach (var n in nums)
        counts[n] = counts.GetValueOrDefault(n) + 1;

    var heap = new MinHeap<(int freq, int num)>();
    foreach (var kv in counts)
    {
        heap.Push((kv.Value, kv.Key));
        if (heap.Count > k) heap.Pop();
    }

    var result = new List<int>();
    while (heap.Count > 0) result.Add(heap.Pop().num);
    return result;
}

// Note: .NET 6+ ships a built-in System.Collections.Generic.PriorityQueue<TElement,TPriority>
// which should be preferred in production code — implement the custom heap only to
// demonstrate understanding in an interview.

Complexity

Operation Time
Push / Pop O(log n)
Peek O(1)
Build heap from array (heapify) O(n) — not O(n log n), by amortized analysis

Follow-up: “Why is heapify O(n) and not O(n log n)?” Because most nodes are near the bottom of the tree with a short distance to sift down; summing sift-down cost across all levels converges to O(n), not O(n log n).