Skip to main content
Intermediate ~15 min read

Heaps & Priority Queues

The min-at-top structure that never fully sorts: peek in O(1), insert/extract in O(log n), and a hidden array representation.

Prerequisites: Binary Trees & Traversals, Big O Notation & Time Complexity

A heap answers one question instantly: "what's the smallest (or largest)?" The min-heap invariant: every parent ≤ both children. That's weaker than a BST's total order, siblings and cousins are unordered, but it guarantees the minimum is always at the root, and it's strong enough to maintain in O(log n) per operation. This structure is called a priority queue: instead of FIFO or LIFO, the most urgent element leaves first.

Insert: place the new element at the next open slot (bottom level), then bubble it UP while it's smaller than its parent. Extract-min: remove the root, move the last element to the root, then sift it DOWN by swapping with its smaller child. Each operation touches one root-to-leaf path, O(log n). The delightful implementation detail: none of this needs pointers. A heap lives in a plain array where the children of index i are 2i+1 and 2i+2 and the parent is ⌊(i−1)/2⌋, the tree is just an interpretation of the array's order.

Array-backed min-heap

min-heap.js
class MinHeap {
  #a = [];
  get size() { return this.#a.length; }
  peek() { return this.#a[0]; }               // O(1), the whole point

  push(v) {                                    // O(log n)
    this.#a.push(v);
    let i = this.#a.length - 1;
    while (i > 0) {                            // bubble up
      const parent = (i - 1) >> 1;
      if (this.#a[parent] <= this.#a[i]) break;
      [this.#a[parent], this.#a[i]] = [this.#a[i], this.#a[parent]];
      i = parent;
    }
  }

  pop() {                                      // O(log n)
    const top = this.#a[0];
    const last = this.#a.pop();
    if (this.#a.length) {
      this.#a[0] = last;
      let i = 0;
      for (;;) {                               // sift down
        const l = 2 * i + 1, r = 2 * i + 2;
        let smallest = i;
        if (l < this.#a.length && this.#a[l] < this.#a[smallest]) smallest = l;
        if (r < this.#a.length && this.#a[r] < this.#a[smallest]) smallest = r;
        if (smallest === i) break;
        [this.#a[i], this.#a[smallest]] = [this.#a[smallest], this.#a[i]];
        i = smallest;
      }
    }
    return top;
  }
}
Operation / caseCostNotes
peek (min/max)O(1)root
insertO(log n)bubble up one path
extract min/maxO(log n)sift down one path
build from n items (heapify)O(n)bottom-up construction beats n inserts
search arbitrary valueO(n)heaps are NOT for searching

Check your understanding

  1. 1.How does a min-heap differ from a BST?
  2. 2.In the array representation, the children of index 3 are:
  3. 3.Finding the 3 largest values in a stream of millions of numbers, without storing everything: which structure and size?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going