Skip to the content

Lesson 139 of 296

Heaps: build a MinHeap

What you will learn

  • What a heap is and what it is for
  • Storing a heap in an array
  • Push (sift up) and pop (sift down)
  • A reusable generic heap class in TypeScript
  • Heapify and heap sort
On this page

What is a heap?

A heap is a tree-shaped structure that always gives you the smallest item (a min-heap) or the largest item (a max-heap) quickly.

OperationCost
Peek at the smallestO(1)
Push a new itemO(log n)
Pop the smallestO(log n)
Build from n itemsO(n)

It is the standard way to build a priority queue (Lesson 129). Used in: top-k problems, merging sorted lists, scheduling, Dijkstra's shortest path (Lesson 143).

JavaScript has no built-in heap. In interviews you must often write one, so practise it until you can write it from memory in about 10 minutes.

The heap rules

A binary min-heap is:

  1. A complete binary tree: every level is full except possibly the last, which fills from the left.
  2. Heap-ordered: every parent is less than or equal to its children.

The smallest item is always at the root. (Unlike a BST, there is no left/right ordering between siblings.)

Stored in an array

Because the tree is complete, it fits in an array with no gaps. For the item at index i:

RelationIndex
ParentMath.floor((i - 1) / 2)
Left child2 * i + 1
Right child2 * i + 2
Tree:            1
               /   \
              3     2
             / \   /
            7   4 5

Array:  [1, 3, 2, 7, 4, 5]
index:   0  1  2  3  4  5

Push: sift up

Add the new item at the end of the array, then swap it with its parent while it is smaller than the parent.

Pop: sift down

Remove the root (the smallest). Move the last item to the root, then swap it with its smaller child while it is larger than that child.

A generic Heap class

Using a comparator (Lesson 121) makes one class work as a min-heap, a max-heap, or a heap of objects:

TypeScript
class Heap<T> {
  private items: T[] = [];

  constructor(private compare: (a: T, b: T) => number) {}

  get size(): number {
    return this.items.length;
  }

  peek(): T | undefined {
    return this.items[0];
  }

  push(item: T): void {
    this.items.push(item);
    this.siftUp(this.items.length - 1);
  }

  pop(): T | undefined {
    const items = this.items;
    if (items.length === 0) return undefined;
    const top = items[0]!;
    const last = items.pop()!;
    if (items.length > 0) {
      items[0] = last;
      this.siftDown(0);
    }
    return top;
  }

  private siftUp(index: number): void {
    const items = this.items;
    while (index > 0) {
      const parent = Math.floor((index - 1) / 2);
      if (this.compare(items[index]!, items[parent]!) >= 0) break;
      [items[index], items[parent]] = [items[parent]!, items[index]!];
      index = parent;
    }
  }

  private siftDown(index: number): void {
    const items = this.items;
    const n = items.length;
    while (true) {
      const left = 2 * index + 1;
      const right = left + 1;
      let smallest = index;
      if (left < n && this.compare(items[left]!, items[smallest]!) < 0) smallest = left;
      if (right < n && this.compare(items[right]!, items[smallest]!) < 0) smallest = right;
      if (smallest === index) break;
      [items[index], items[smallest]] = [items[smallest]!, items[index]!];
      index = smallest;
    }
  }
}

Usage:

TypeScript
function heapDemo(): number[] {
  const minHeap = new Heap<number>((a, b) => a - b);
  for (const n of [5, 1, 8, 3, 2]) minHeap.push(n);
  const sorted: number[] = [];
  while (minHeap.size > 0) sorted.push(minHeap.pop()!);
  return sorted;
}

heapDemo() returns [1, 2, 3, 5, 8]. For a max-heap, use (a, b) => b - a. For objects: new Heap<Task>((a, b) => a.priority - b.priority).

Why O(log n)? A complete tree with n items has height about log₂ n, and sift up or down moves at most one level per swap.

Heapify and heap sort

Building a heap by pushing n items one at a time is O(n log n). Heapify builds it in O(n) by calling sift-down on every non-leaf node from the bottom up (most nodes are near the bottom and move very little).

Heap sort: heapify, then pop n times: O(n log n) time, O(1) extra space when done in place.

How to say it in an interview

"A binary heap is a complete binary tree stored in an array, where each parent is smaller than its children in a min-heap, so the minimum is at index zero. Children of i are at 2i plus 1 and 2i plus 2, the parent at i minus 1 over 2. Push appends and sifts up; pop moves the last element to the root and sifts down, both O(log n), and peek is O(1). JavaScript has no built-in heap, so I write a generic one with a comparator, which works as min-heap, max-heap or priority queue of objects."

Key words

WordMeaning
HeapA tree that gives the min or max quickly
Min-heap / max-heapSmallest / largest item at the root
Complete binary treeEvery level full except the last, filled from the left
Sift up / sift downMoving an item up or down to restore heap order
HeapifyBuilding a heap from an array in O(n)
Priority queueA queue that removes the highest-priority item first

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.