Data Structures and Algorithms, Pattern by Pattern / Module 08

Module 8: Heaps

Store a binary heap in an array, keep the top k of a large list, track a running median, and find the cheapest paths with Dijkstra's algorithm.

Suppose you have a million scores and need the ten highest. The direct way sorts all of them, highest first, and keeps the first ten. Save it as opening-slow.ts:

// Opening problem: the ten highest of a million scores. The slow version: node opening-slow.ts
import { bench } from "./bench.ts";

// n random whole-number scores from 0 to 999,999.
export function makeScores(n: number): number[] {
  return Array.from({ length: n }, () => Math.floor(Math.random() * 1_000_000));
}

// Sort a copy of every score, highest first, and keep the first ten.
// O(n log n) time, O(n) extra memory for the copy.
export function topTenSort(scores: number[]): number[] {
  return scores.toSorted((a, b) => b - a).slice(0, 10);
}

if (process.argv[1] === import.meta.filename) {
  const scores = [5, 100, 25, 1000, 9, 80, 300];
  console.log("top ten of", scores.join(" "), "->", topTenSort(scores).join(" "));
  bench("topTenSort", [250_000, 500_000, 1_000_000], makeScores, topTenSort);
}

The function is correct, but it puts every score in order and then reads ten of them. This module builds a heap, a structure that always knows its smallest item, and uses it to keep only the ten best so far. Then the same heap tracks a median, merges sorted lists and finds the cheapest route on a map.

After this module, you can:

  • store a binary heap in an array, and write its push and pop in O(log n)
  • keep the k largest of n items in O(n log k), and say when a full sort is the better choice
  • build a heap from a whole list in O(n)
  • keep a running median with two heaps, and merge k sorted lists
  • find the cheapest paths in a graph whose edges have different costs, with Dijkstra’s algorithm

Measure the full sort

Make a folder for the module, as in Module 1, and copy bench.ts into it unchanged:

mkdir module-08 && cd module-08 && echo '{ "type": "module" }' > package.json

Every file this module runs is also in the module-08 folder of the course’s code repository.

Pause and predict. topTenSort sorts every score to keep ten. With 250,000, 500,000 and 1,000,000 scores, how much longer does each doubling take?

Here is what node opening-slow.ts printed:

top ten of 5 100 25 1000 9 80 300 -> 1000 300 100 80 25 9 5

topTenSort
             n   median ms   x prev
       250,000       66.51
       500,000      137.82      2.1
     1,000,000      292.75      2.1

Every table in this module comes from one run on an Intel Core i7-9750H laptop (x86_64, 6 cores, macOS) with Node.js 26.13.1. Your numbers will differ, but the ratios should look alike.

The time grew 2.1 times per doubling, which is what n log n predicts at these sizes. toSorted is O(n log n) time (Module 1), and its copy is O(n) memory. So a million scores cost about 290 ms.

The waste is in the order. The sort puts 999,990 scores in order, and nobody reads them.

Rule: When you need a few items from the top of a large list, don’t order the whole list.

Keep only the ten best so far

Read the scores one at a time and keep the ten best seen so far. A new score matters only if it beats the weakest of the ten. Then the weakest leaves and the new score joins.

So you need a collection that answers three requests fast:

  • “which is the smallest?”
  • “remove the smallest”
  • “add this one”

A priority queue is a collection that answers them. You add items in any order, and you always take out the one that comes first by some rule, here the smallest score.

Why not keep the ten in a plain array? For k items, a scan for the smallest costs O(k) per change. For k = 10 that’s cheap, but for the top 10,000 of a stream, each scan reads 10,000 items. A sorted array finds the smallest at once, but inserting into it shifts up to k items, also O(k).

A binary heap does both in O(log k). The next five sections build one.

A heap is a tree with the smallest item on top

In a binary tree (Module 6), each node has at most two children, and the node at the top is the root. A binary heap is a binary tree where every parent comes out before its children. That condition is the heap property.

A min-heap is a heap where “comes out first” means “is smaller”. So every parent is smaller than its children, and the smallest item is at the root.

Figure 1 shows the min-heap that seven pushes build from the scores 5, 100, 25, 1000, 9, 80 and 300. The array row is what trace-demo.ts prints.

                    [5]                      level 0: index 0
                 /       \
             [9]           [25]              level 1: indexes 1 and 2
            /   \         /    \
       [1000]  [100]   [80]   [300]          level 2: indexes 3 to 6

array   [   5][   9][  25][1000][ 100][  80][ 300]
index      0     1     2     3     4     5     6

Figure 1: the tree has no pointers, because a node’s position in the array says where its parent and children are.

The heap property says nothing about the order of two siblings. 1000 sits left of 100, for example. So a heap is not a sorted array, and only the root is sure to be the smallest.

The tree lives in an array

A complete binary tree has every level full, except maybe the last, which fills from the left. A heap is always complete, so you can store it level by level in an array with no gaps, as the array row of Figure 1 shows.

Then index math replaces pointers. With the root at index 0, the children of index i are at 2i + 1 and 2i + 2. Its parent is at (i − 1) >> 1. The operator >> 1 shifts the bits one place right, which halves a non-negative whole number and drops the remainder: 5 >> 1 is 2.

So the children of 9, at index 1, are at 3 and 4: 1000 and 100. Index 6 (300) has its parent at (6 − 1) >> 1 = 2, which is 25.

Each level holds twice as many items as the one above. So a complete tree of n items has about log₂ n levels: 7 items fit in 3 levels, and a million in 20. That height is the cost of every change to the heap.

Push: the new item climbs

To push, put the new item at the end of the array, the next free place on the last level. That may break the heap property between it and its parent. So compare the two, and move the parent down while the new item should come out first.

Sift up is this climb: move an item toward the root until its parent comes out before it, or it is the root. Figure 2 traces push(7) on the heap from Figure 1, as trace-demo.ts prints it. heap.ts does not swap at each step. It moves each parent down into the hole and writes 7 once at the end.

hole at   compare with parent        array (_ is the hole)
7         -                          5 9 25 1000 100 80 300 _
3         7 < 1000 (index 3): move   5 9 25 _ 100 80 300 1000
1         7 < 9 (index 1): move      5 _ 25 9 100 80 300 1000
1         7 < 5 (index 0)? no        stop
write 7                              5 7 25 9 100 80 300 1000

Figure 2: 7 climbs two levels and stops below 5, so a push compares at most once per level, O(log n).

Pop: the last item sinks

To pop, take the root, which is the item that comes out next. Then move the last item of the array to the root, so the tree stays complete. That item is probably too large for the root, so it must sink.

Sift down is this sinking: move an item away from the root, swapping it with the child that comes out first, until both children come out after it. Figure 3 traces pop() on the heap after the push, as trace-demo.ts prints it.

hole at   children, smaller one       array (_ is the hole)
0         5 out, 1000 sinks           _ 7 25 9 100 80 300
1         7, 25: 7 < 1000, move       7 _ 25 9 100 80 300
3         9, 100: 9 < 1000, move      7 9 25 _ 100 80 300
3         none                        stop
write 1000                            7 9 25 1000 100 80 300

Figure 3: the last item, 1000, sinks two levels toward the smaller child each time, so a pop also costs O(log n).

Each step of a sift down compares the two children, then the smaller one with the sinking item. So a pop makes at most two comparisons per level, and a push one.

The heap in TypeScript

Save heap.ts. Later modules import this file, so keep it in the module folder:

// A binary heap stored in an array. `before(a, b)` returns true when a must
// come out before b: (a, b) => a < b gives a min-heap, (a, b) => a > b a max-heap.
// Index math, 0-based: parent of i is (i - 1) >> 1, children are 2i + 1 and 2i + 2.
// Later modules import this file.
export class Heap<T> {
  private items: T[];
  private before: (a: T, b: T) => boolean;

  // Builds a heap from `items` in O(n): sift down every parent, from the last
  // one to the root. The array is used in place, not copied.
  constructor(before: (a: T, b: T) => boolean, items: T[] = []) {
    this.before = before;
    this.items = items;
    for (let i = (items.length >> 1) - 1; i >= 0; i--) this.siftDown(i);
  }

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

  // The item that comes out next. O(1).
  peek(): T | undefined {
    return this.items[0];
  }

  // O(log n): the new item climbs at most the height of the tree.
  push(item: T): void {
    this.items.push(item);
    this.siftUp(this.items.length - 1);
  }

  // O(log n): the last item moves to the root and sinks.
  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;
  }

  // Swap out the top for `item` in one sift: cheaper than pop() then push().
  replaceTop(item: T): T | undefined {
    const top = this.items[0];
    this.items[0] = item;
    this.siftDown(0);
    return top;
  }

  private siftUp(i: number): void {
    const items = this.items;
    const item = items[i];
    while (i > 0) {
      const parent = (i - 1) >> 1;
      if (!this.before(item, items[parent])) break;
      items[i] = items[parent]; // move the parent down; place `item` once at the end
      i = parent;
    }
    items[i] = item;
  }

  private siftDown(i: number): void {
    const items = this.items;
    const n = items.length;
    const item = items[i];
    while (true) {
      let child = 2 * i + 1;
      if (child >= n) break;
      if (child + 1 < n && this.before(items[child + 1], items[child])) child++;
      if (!this.before(items[child], item)) break;
      items[i] = items[child];
      i = child;
    }
    items[i] = item;
  }
}

before(a, b) returns true when a must come out before b. (a, b) => a < b gives a min-heap. A max-heap has the largest item at the root, and (a, b) => a > b gives one. For objects, compare a field: (a, b) => a.at < b.at.

The comparison returns a boolean, unlike the number that Array.prototype.sort takes. So passing (a, b) => a - b here builds a wrong heap with no error.

The costs:

  • peek reads index 0: O(1).
  • push and pop sift along one path from the root to the bottom: O(log n) time.
  • replaceTop swaps the top for a new item with one sift down. That’s half the work of a pop followed by a push.
  • The heap takes O(n) memory, one array slot per item.

The constructor takes an array and turns it into a heap in place. A later section explains why that loop is O(n).

Rule: A heap keeps only one promise: the item at index 0 comes out first. Push and pop restore that promise along one path, in O(log n).

The top ten with a heap

Now keep the ten best scores in a min-heap. Its root is the weakest of the ten, so a new score is compared with the root only. If it is larger, replaceTop puts it in and sinks it.

Figure 4 traces the top 3 of the seven scores from Figure 1, as trace-demo.ts prints it. The heap column is the array.

score   heap array    action
5       5             push
100     5 100         push
25      5 100 25      push
1000    25 100 1000   1000 > 5: replace the top
9       25 100 1000   9 > 25? no: skip
80      80 100 1000   80 > 25: replace the top
300     100 300 1000  300 > 80: replace the top
pop all: 100 300 1000, reversed: 1000 300 100

Figure 4: the root is always the weakest of the three kept, so 9 is rejected with one comparison and never enters the heap.

The heap pops its items weakest first, so the function reverses them at the end. This excerpt from opening-fast.ts is the whole function. The file in the repository adds the imports and the benchmark calls.

// excerpt from opening-fast.ts
// Keep the k best scores seen so far in a min-heap. Its top is the weakest of the k,
// the only one a new score has to beat. O(n log k) time, O(k) extra memory.
export function topKHeap(scores: number[], k = 10): number[] {
  const best = new Heap<number>((a, b) => a < b);
  for (const s of scores) {
    if (best.size < k) best.push(s);
    else if (k > 0 && s > best.peek()!) best.replaceTop(s); // drop the weakest, sift the new score down
  }
  const out: number[] = [];
  while (best.size > 0) out.push(best.pop()!); // weakest first
  return out.reverse();
}

Each score costs one comparison with peek(), plus O(log k) when it enters the heap. So topKHeap is O(n log k) time, and O(k) extra memory for the heap. In other words, with k fixed at 10, the time grows in step with n.

node opening-fast.ts runs the sort again, then the heap on the same sizes and on larger ones:

top 3 of 5 100 25 1000 9 80 300 -> 1000 300 100

topTenSort
             n   median ms   x prev
       250,000       66.65
       500,000      134.77      2.0
     1,000,000      288.89      2.1

topKHeap
             n   median ms   x prev
       250,000        6.63
       500,000        1.05      0.2
     1,000,000        2.11      2.0

topKHeap, larger
             n   median ms   x prev
     2,000,000        4.43
     4,000,000        8.69      2.0
     8,000,000       17.71      2.0

At 1,000,000 scores, the time went from 288.89 ms to 2.11 ms. Figure 5 draws both.

median ms for the top ten of n scores (each # is about 6.5 ms)

n =   250,000   sort   ##########                                      66.65
                heap   #                                                6.63
n =   500,000   sort   #####################                          134.77
                heap   |                                                1.05
n = 1,000,000   sort   ############################################   288.89
                heap   |                                                2.11

Figure 5: the sort grows a little more than 2 times per doubling, while the heap stays near 2 ms at a million scores.

The first heap row is slower than the second, because Node.js was still compiling the function to faster code during those first runs. “Going deeper” shows the run times one by one. So read the growth from 500,000 up: 2.0 times per doubling, all the way to 8,000,000 scores.

The heap also changes rarely on random scores. Only about 124 of a million scores entered the heap, as “Going deeper” counts, and every other score cost one comparison.

Rule: For the k largest items, keep a min-heap of size k. Its root is the weakest item kept, the only one a new item must beat.

Build a heap from a whole list in O(n)

When all the items are there at the start, you can push them one by one, at O(log n) each. Or you can build the heap in place, as the constructor of heap.ts does.

A leaf is a node with no children, so a leaf alone is already a heap. A bottom-up build sifts down every parent, from the last parent back to the root. The last half of the array is leaves, so the loop starts at index (n >> 1) − 1.

Pause and predict. A push costs O(log n), so n pushes look like O(n log n). For 1,000,000 random values, how many comparisons per item do the pushes make, and how many does the bottom-up build make?

build-count.ts counts the calls to the comparison function, then times both ways. The “rising” columns feed values in rising order into a max-heap.

compares per item
           n    pushes   bottom-up   pushes, rising   bottom-up, rising
       1,000      2.18        1.83             7.99                1.98
      10,000      2.25        1.88            11.36                2.00
     100,000      2.28        1.88            14.69                2.00
   1,000,000      2.28        1.88            17.95                2.00

heap by n pushes
             n   median ms   x prev
     1,000,000       57.07
     2,000,000      121.97      2.1
     4,000,000      256.32      2.1

heap bottom-up
             n   median ms   x prev
     1,000,000       26.41
     2,000,000       56.16      2.1
     4,000,000      116.19      2.1

Random pushes made 2.18 to 2.28 comparisons per item at every size, so a random push climbs about one level. Rising values make every push climb to the root. Then the comparisons per item grew with the height: 7.99 at 1,000 and 17.95 at 1,000,000. That’s the O(n log n) worst case.

The bottom-up build stayed at 1.83 to 2.00 comparisons per item, rising or not. Why doesn’t it pay log n per item too? Half the nodes are leaves and never sink, and most of the rest sit near the bottom and sink a level or two. Only the root can sink the whole height.

So the build is O(n), and it was twice as fast as the pushes: 116.19 ms against 256.32 ms at 4,000,000 values.

Rule: If you have all the items before the first pop, pass them to the constructor: O(n), not O(n log n).

Cheapest paths: Dijkstra’s algorithm

Module 7 found the fewest steps with BFS, because every step cost the same. Now the steps cost different amounts.

A weighted graph is a graph whose edges each carry a number, called a cost or a weight. Figure 6 is a small road map. Node 0 is a depot, and each road is one-way, with its cost in minutes:

  • 0 → 1 costs 4, and 0 → 2 costs 1
  • 2 → 1 costs 2, and 2 → 3 costs 5
  • 1 → 3 costs 1, and 3 → 4 costs 3
           4
   [0] ---------> [1]
    |              ^  \
  1 |            2 |   \ 1
    v              |    v
   [2] ------------+    [3] ---3---> [4]
    |                    ^
    +--------- 5 --------+

Figure 6: BFS reaches node 3 in two roads, for 5 or 6 minutes. The cheapest way takes three roads, 0 → 2 → 1 → 3, for 4 minutes.

So the fewest edges is no longer the cheapest path.

Dijkstra’s algorithm finds the cheapest paths from one start node to all the others, when no cost is negative. Edsger W. Dijkstra published it in a 1959 paper.

The idea is to finish the nodes in order of their distance from the start. Take the unfinished node with the smallest known distance, and call its distance final. Then lower the known distance of each node it has a road to, if the road through it is cheaper.

Why is that distance final? Any other path to the node must leave the finished nodes through some node that is at least as far. Costs only add, so that path can’t come out cheaper.

In the paper, each round finds the closest unfinished node by scanning all of them. With V nodes and E edges, that’s O(V) per round and O(V²) in all. A heap can hand over the closest node in O(log V) instead.

Dijkstra with a heap

dijkstraHeap keeps [distance, node] entries in a min-heap, so the closest unfinished node comes out first. This excerpt is the function from dijkstra.ts. The full file in the repository adds the graph types, a random graph maker, the road map of Figure 6, the scan version dijkstraScan and the benchmark.

// excerpt from dijkstra.ts
// Dijkstra with a binary heap and lazy deletion: when a node's distance improves, push a new
// entry and leave the old one in the heap; skip an entry whose node is already done.
// O(E log V) time, O(V + E) memory (the heap can hold one entry per edge).
export function dijkstraHeap(graph: Graph, source: number): Float64Array {
  const dist = new Float64Array(graph.length).fill(Infinity);
  const done = new Uint8Array(graph.length);
  const heap = new Heap<[number, number]>((a, b) => a[0] < b[0]); // [distance, node]
  dist[source] = 0;
  heap.push([0, source]);
  while (heap.size > 0) {
    const [d, u] = heap.pop()!;
    if (done[u]) continue; // a stale entry: u was finished with a smaller distance
    done[u] = 1;
    for (const [to, cost] of graph[u]) {
      if (d + cost < dist[to]) {
        dist[to] = d + cost;
        heap.push([dist[to], to]);
      }
    }
  }
  return dist;
}

graph[u] is the list of roads out of node u, each a [to, cost] pair. A node’s distance can drop after the node is already in the heap, as node 1’s does in the map. A heap can’t find an entry to change it, so dijkstraHeap pushes a second entry and leaves the old one.

Lazy deletion is leaving an out-of-date entry in the heap and skipping it when it comes out. Here an entry is out of date, or stale, when its node is already done.

Figure 7 traces dijkstraHeap on the road map, as trace-demo.ts prints it. Each heap entry is [distance, node], and - in the distances means “not reached yet”.

pop      action           dist 0..4    heap entries, smallest first
start    -                0 - - - -    [0,0]
[0,0]    finish 0         0 4 1 - -    [1,2] [4,1]
[1,2]    finish 2         0 3 1 6 -    [3,1] [4,1] [6,3]
[3,1]    finish 1         0 3 1 4 -    [4,1] [4,3] [6,3]
[4,1]    1 done: skip     0 3 1 4 -    [4,3] [6,3]
[4,3]    finish 3         0 3 1 4 7    [6,3] [7,4]
[6,3]    3 done: skip     0 3 1 4 7    [7,4]
[7,4]    finish 4         0 3 1 4 7    -

Figure 7: node 1 enters the heap at 4, then again at 3 through node 2; the entry at 3 finishes it, and the stale entry [4,1] is skipped.

Every edge can push at most one entry, so the heap holds at most E entries, and each push or pop costs O(log E). E is at most V², so log E is at most 2 log V. So dijkstraHeap is O(E log V) time and O(V + E) memory, against O(V² + E) time for the scan.

node dijkstra.ts checks both versions on the map and on a random graph with 4 roads out of each node, then times them:

small map, scan: 0 3 1 4 7  heap: 0 3 1 4 7
3,000 random nodes: same distances: true, reached 2948

dijkstraScan
             n   median ms   x prev
         4,000       43.29
         8,000      173.51      4.0
        16,000      722.40      4.2

dijkstraHeap
             n   median ms   x prev
         4,000        2.12
         8,000        3.35      1.6
        16,000        9.73      2.9

dijkstraHeap, larger
             n   median ms   x prev
       100,000      108.76
       200,000      292.67      2.7
       400,000      707.21      2.4

At 16,000 nodes, the time went from 722.40 ms to 9.73 ms. The scan grew 4 times per doubling, as O(V²) predicts.

The heap times under 10 ms are too noisy to read growth from, so the larger sizes show it. There the heap grew 2.7 and 2.4 times per doubling, a little more than the 2.1 that E log V predicts. In nine runs, that ratio ranged from 1.9 to 3.1.

The heap is not always the winner. On a dense graph, where most pairs of nodes have a road, E is close to V². Then O(E log V) is O(V² log V), and the plain scan, O(V²), is the better choice.

Rule: For the cheapest paths when steps cost different amounts and none is negative, finish nodes closest first with a min-heap, and skip the entries of nodes already done.

A negative cost breaks it

The proof above says that costs only add. With a negative cost, a node can be finished, and a cheaper path to it can appear later.

negative-edge.ts gives the map a rebate: 0 → 1 costs 2, 0 → 2 costs 3, 2 → 1 costs −2 and 1 → 3 costs 1. Run node negative-edge.ts:

dijkstraHeap: [ 0, 1, 3, 3 ]
Bellman-Ford: [ 0, 1, 3, 2 ]

Node 1 was finished at 2, and its road to node 3 set node 3 to 3. Then the road from node 2 lowered node 1 to 1. But node 1 was done, so its road was never used again, and node 3 stayed at 3 with no error. The cheapest path costs 2.

The second line comes from the Bellman-Ford algorithm, which handles negative costs in time proportional to E · V, as Sedgewick and Wayne’s section 4.4 explains.

Two more shapes of the heap pattern

The heap shows up in two more shapes, each with a sign in the problem that points to it. Both live in variations.ts, and node variations.ts printed:

medians after 5 15 1 3 8: 5 10 5 4 5
merged: 1 2 3 4 5 9 10
same median: true

A running median with two heaps

Suppose response times arrive one at a time, and after each one you want the median so far. The median is the middle value once the values are sorted. With an even count, it is the mean of the two middle values.

Keep the smaller half of the values in a max-heap, low, and the larger half in a min-heap, high. The two roots then sit on either side of the middle.

Each new value goes into low if it is at most low‘s root, and into high otherwise. Then one value moves across if needed, so low holds as many values as high, or one more. Figure 8 traces RunningMedian on 5, 15, 1, 3 and 8, as trace-demo.ts prints it. Each heap is listed in sorted order to make it easy to read.

add   low, largest first   high, smallest first   median
5     5                    -                      5
15    5                    15                     10
1     5 1                  15                     5
3     3 1                  5 15                   4
8     5 3 1                8 15                   5

Figure 8: after 3 arrives, low holds three values and high one, so 5 moves across, and the median is the mean of the two roots.

This excerpt from variations.ts is the class:

// excerpt from variations.ts
// The median of every value added so far. `low` is a max-heap with the smaller half,
// `high` a min-heap with the larger half, and low holds the same count as high or one more.
// add: O(log n). median: O(1). O(n) memory.
export class RunningMedian {
  private low = new Heap<number>((a, b) => a > b);
  private high = new Heap<number>((a, b) => a < b);

  add(x: number): void {
    if (this.low.size === 0 || x <= this.low.peek()!) this.low.push(x);
    else this.high.push(x);
    // Move one value across so that low.size is high.size or high.size + 1.
    if (this.low.size > this.high.size + 1) this.high.push(this.low.pop()!);
    else if (this.high.size > this.low.size) this.low.push(this.high.pop()!);
  }

  median(): number | undefined {
    if (this.low.size === 0) return undefined;
    if (this.low.size > this.high.size) return this.low.peek();
    return (this.low.peek()! + this.high.peek()!) / 2;
  }
}

add costs O(log n), for at most three heap operations. median reads two roots in O(1), and the heaps take O(n) memory. The sign is “the median (or a percentile) so far”, asked after every new value.

Pause and predict. lastMedianSorted, also in variations.ts, keeps one sorted array instead. A scan finds the place for each value, and splice inserts it, O(n) per value. Which version is faster for 1,000 values, and which for 100,000?

lastMedianSorted, small
             n   median ms   x prev
         1,000        0.19
         4,000        2.37     12.4
        16,000       32.37     13.7

lastMedianHeaps, small
             n   median ms   x prev
         1,000        0.36
         4,000        1.00      2.8
        16,000        4.06      4.1

lastMedianSorted
             n   median ms   x prev
        25,000       81.34
        50,000      336.28      4.1
       100,000     1432.78      4.3

lastMedianHeaps
             n   median ms   x prev
        25,000        6.06
        50,000       12.78      2.1
       100,000       26.24      2.1

At 1,000 values the sorted array won, 0.19 ms against 0.36 ms, so below a few thousand values the simpler structure is fine. By 4,000 the heaps won, and at 100,000 they took 26.24 ms against 1,432.78 ms. The sorted array grew about 4 times per doubling, O(n²) in all, and the heaps 2.1 times, O(n log n).

Merging k sorted lists

Suppose k servers each write a log sorted by time, and you need one log sorted by time. The next line of the merged log is the smallest of the k first lines not yet taken. So keep one entry per list in a min-heap: [value, list, position].

Figure 9 traces mergeSorted on three lists, as trace-demo.ts prints it.

take   heap entries [value,list,position], smallest first   output
-      [1,0,0] [2,1,0] [5,2,0]                             -
1      [2,1,0] [4,0,1] [5,2,0]                             1
2      [3,1,1] [4,0,1] [5,2,0]                             1 2
3      [4,0,1] [5,2,0] [10,1,2]                            1 2 3
4      [5,2,0] [9,0,2] [10,1,2]                            1 2 3 4
5      [9,0,2] [10,1,2]                                    1 2 3 4 5
9      [10,1,2]                                            1 2 3 4 5 9
10     -                                                   1 2 3 4 5 9 10

Figure 9: the heap never holds more than one entry per list, and taking an entry brings in the next value of the same list.

This excerpt from variations.ts is the function:

// excerpt from variations.ts
// Merge k sorted lists into one sorted list. The heap holds one entry per list:
// [value, list index, position]. O(N log k) time for N values in all, O(k) extra memory.
export function mergeSorted(lists: number[][]): number[] {
  const heap = new Heap<[number, number, number]>((a, b) => a[0] < b[0]);
  lists.forEach((list, i) => { if (list.length > 0) heap.push([list[0], i, 0]); });
  const out: number[] = [];
  while (heap.size > 0) {
    const [value, i, pos] = heap.peek()!;
    out.push(value);
    if (pos + 1 < lists[i].length) heap.replaceTop([lists[i][pos + 1], i, pos + 1]); // the next value of the same list
    else heap.pop(); // that list is used up
  }
  return out;
}

Each of the N values enters and leaves a heap of at most k entries. So mergeSorted is O(N log k) time, and O(k) extra memory beside the output.

Joining the lists and sorting the result is O(N log N). That’s fine when N is small, and it is the simpler choice when the lists are not sorted to begin with. The sign is “k sorted inputs, one sorted output”.

Underneath: heaps in JavaScript

The heap is one plain array

A heap of numbers lives in one JavaScript array. Module 1 showed that each array slot is 8 bytes in this Node.js build, and a whole number or a fraction sits in the slot itself.

Module 6 built a tree from node objects with pointers. A heap needs none, because the tree is always complete. So a position in the array is enough to find a parent or a child.

An entry like [distance, node] costs more, because it is a small array of its own. “Going deeper” measures how much.

JavaScript has no priority queue

As of November 2026, the current ECMA-262 draft has no priority queue or heap. No proposal for one exists at any stage, according to the TC39 proposals list. So you write one, as this module did, or take one from a package.

Nothing about heaps changed recently. The newest method this module uses, toSorted, is from ES2023, as the TC39 finished proposals list under “Change Array by Copy”.

Sort, quickselect or a heap

alternatives.ts times two other ways to get the top ten. It also times the heap against a full sort when k grows with n.

A Float64Array is a typed array: it holds only numbers, so it sorts them by value with no comparison function.

Quickselect splits the array around a random pivot again and again, keeping only the side that holds the k-th item. C. A. R. Hoare published it as “Find” in a 1961 paper.

Pause and predict. For the top half of 1,000,000 random scores, k = n / 2, is a heap of size k or a full sort faster?

Here are the times at 1,000,000 scores, from alternatives.ts and opening-fast.ts:

Method Time Extra memory ms in one run
toSorted with a comparator, keep 10 (opening-fast.ts) O(n log n) O(n) 288.89
Float64Array sort, keep 10 O(n log n) O(n) 93.34
Quickselect, then sort 10 O(n) expected, O(n²) worst O(n) 7.22
Heap of size 10 (opening-fast.ts) O(n log k) O(k) 2.11
Heap of size n / 10 O(n log k) O(k) 39.87
Heap of size n / 2 O(n log k) O(k) 115.65

The typed array was 3 times faster than toSorted, but it works only for numbers. Quickselect is O(n) on average, but it copies the whole array, and its worst case is O(n²) when the pivots keep landing badly.

The heap kept winning even at k = n / 2, 115.65 ms against 295.13 ms for the full sort. So on random numbers, the case for a sort at a large k is simpler code, not speed. When you need every item in order anyway, sort.

Common mistakes

mistakes.ts writes four bugs that are easy to make with heaps, and prints what each one returns. Run node mistakes.ts:

1. top 3 with a max-heap: 1000 25 5
2. comparator a - b: 300 80 100 9 25 1000 5
3. 1-based math, root at 0: 5 1 9 (the root should be 1)
4. equal priorities: a e d c b  with a sequence number: a b c d e

A max-heap for the top k. The root of a max-heap is the best score kept, so each new score is compared with the wrong one. The top 3 of 5 100 25 1000 9 80 300 came out as 1000 25 5. For the k largest, use a min-heap of size k; for the k smallest, a max-heap.

A comparison that returns a number. (a, b) => a - b is right for sort, but heap.ts reads the result as true or false. Every non-zero difference is true, so the heap popped 300 80 100 9 25 1000 5. Pass (a, b) => a < b.

1-based index math on a 0-based array. With the root at index 0, “children at 2i and 2i + 1” makes the root its own child. Then the root is never compared with index 2. The heap 9 5 1 was built as 5 1 9, with 5 on top instead of 1. Use children at 2i + 1 and 2i + 2, and the parent at (i − 1) >> 1.

Expecting ties in the order they came in. Five jobs with the same priority came out as a e d c b, because a sift moves items past each other. So a heap is not stable: it does not keep equal items in their arrival order. If ties must keep that order, add a sequence number to each item and compare it when the priorities are equal.

The Dijkstra section showed a fifth mistake, a negative cost. Dijkstra’s algorithm then returns a wrong distance with no error.

Exercises

The exercises are in the module’s exercises folder, each with a test file, and the solutions are in solutions. Each exercise may import the Heap from ../heap.ts. Run all the tests with:

node --test "exercises/*.test.ts"

All 17 tests fail until you write the four answers. Each exercise ends with a test that a correct but slow answer fails on time. The slow folder holds such answers, with a copy of each test.

Exercise 1: merge the log files (easy)

Log files of different sizes are merged two at a time until one file is left. Merging files of a and b MB costs a + b. Always merge the two smallest files.

Write mergeCost(sizes): the total cost. Start from exercises/merge-cost.ts:

// Exercise 1: log files of the given sizes are merged two at a time until one file is left.
// Merging files of a and b MB costs a + b. Always merge the two smallest files.
// Returns the total cost. The input array is not changed.
// You may import the Heap from "../heap.ts".
export function mergeCost(sizes: number[]): number {
  throw new Error("not implemented");
}

For sizes 4, 3, 2 and 6, you merge 2 + 3 = 5, then 4 + 5 = 9, then 6 + 9 = 15. The answer is 29. The last test merges 20,000 files in under 300 ms.

Hint

All the sizes are there before the first merge. Which way of building the heap does that allow? Then each round is two pops and one push.

Solution
// Exercise 1: log files of the given sizes are merged two at a time until one file is left.
// Merging files of a and b MB costs a + b. Always merge the two smallest files.
// Returns the total cost. The input array is not changed.
// A min-heap built bottom-up from a copy; each round pops two and pushes their sum.
// O(n log n) time, O(n) memory.
import { Heap } from "../heap.ts";

export function mergeCost(sizes: number[]): number {
  const files = new Heap<number>((a, b) => a < b, sizes.slice()); // O(n) build from a copy
  let total = 0;
  while (files.size > 1) {
    const merged = files.pop()! + files.pop()!;
    total += merged;
    files.push(merged);
  }
  return total;
}

Cost: O(n) to build the heap from a copy, then n − 1 rounds of two pops and a push at O(log n) each. So O(n log n) time and O(n) memory. slow/merge-cost.ts sorts the files again before every merge. Each sort of an almost sorted array costs about O(n), so that’s O(n²) in all, and it took 2,633 ms on the last test.

Exercise 2: the shortest job first (medium)

One worker runs jobs one at a time, each to the end. Whenever the worker is free, it takes the shortest job that has arrived. Ties go to the earlier arrival, then the smaller id. If no job is waiting, the worker waits for the next one to arrive.

Write jobOrder(jobs): the ids in the order they run. Start from exercises/job-order.ts:

// Exercise 2: one worker runs jobs one at a time, each to the end. Whenever the worker is free,
// it takes the shortest job that has arrived; ties go to the earlier arrival, then the smaller id.
// If no job is waiting, the worker waits for the next one to arrive. Returns the ids in run order.
// You may import the Heap from "../heap.ts".
export type Job = { id: string; arrive: number; length: number };

export function jobOrder(jobs: Job[]): string[] {
  throw new Error("not implemented");
}

For jobs a (arrives at 0, takes 5), b (1, 2), c (2, 1) and d (10, 1), the answer is a c b d. When a ends at 5, both b and c are waiting, and c is shorter. The last test orders 30,000 jobs that arrive within 10 minutes of each other in under 300 ms.

Hint

Sort a copy of the jobs by arrival, and walk through it with an index as time passes. Keep the jobs that have arrived in a heap whose comparison checks the length, then the arrival, then the id. When the heap is empty, move the time forward to the next arrival.

Solution
// Exercise 2: one worker runs jobs one at a time, each to the end. Whenever the worker is free,
// it takes the shortest job that has arrived; ties go to the earlier arrival, then the smaller id.
// If no job is waiting, the worker waits for the next one to arrive. Returns the ids in run order.
// Sort the jobs by arrival, and keep the jobs that have arrived in a heap.
// O(n log n) time, O(n) memory.
import { Heap } from "../heap.ts";

export type Job = { id: string; arrive: number; length: number };

export function jobOrder(jobs: Job[]): string[] {
  const byArrival = jobs.toSorted((a, b) => a.arrive - b.arrive);
  const waiting = new Heap<Job>((a, b) =>
    a.length !== b.length ? a.length < b.length : a.arrive !== b.arrive ? a.arrive < b.arrive : a.id < b.id);
  const order: string[] = [];
  let time = 0;
  let next = 0; // the first job in byArrival that has not arrived yet
  while (order.length < jobs.length) {
    if (waiting.size === 0 && byArrival[next].arrive > time) time = byArrival[next].arrive; // idle until it arrives
    while (next < byArrival.length && byArrival[next].arrive <= time) waiting.push(byArrival[next++]);
    const job = waiting.pop()!;
    order.push(job.id);
    time += job.length;
  }
  return order;
}

Cost: O(n log n) time for the sort and for one push and one pop per job, O(n) memory. Every job enters and leaves the heap once, whatever the arrival times. slow/job-order.ts scans the waiting jobs for the best one, which is O(n) per job and O(n²) in all. It took 2,235 ms on the last test.

Exercise 3: the cheapest way across the map (medium)

A map is a list of rows. A digit 1 to 9 is the minutes it takes to enter that cell, and # can’t be entered. Moving up, down, left or right, write cheapestPath(grid): the fewest minutes from the top-left cell to the bottom-right cell, or -1 if there is no way. The start cell costs nothing.

Start from exercises/cheapest-path.ts:

// Exercise 3: a map of rows where a digit 1 to 9 is the minutes it takes to enter that cell,
// and "#" cannot be entered. Moving up, down, left or right, return the fewest minutes from the
// top-left cell to the bottom-right cell (the start cell costs nothing), or -1 if there is no way.
// You may import the Heap from "../heap.ts".
export function cheapestPath(grid: string[]): number {
  throw new Error("not implemented");
}

For the map 1191, 1991, 1111, the answer is 5: down twice, then right three times. The last test needs a 150 × 150 map in under 300 ms.

Hint

Treat the map as a graph you never build, as with the grids in Module 7. Number cell (r, c) as r * cols + c, and its edges are its open neighbours. The cost of an edge is the digit of the cell it enters. Then run dijkstraHeap‘s loop on the numbered cells, and return as soon as the goal comes out of the heap.

Solution
// Exercise 3: a map of rows where a digit 1 to 9 is the minutes it takes to enter that cell,
// and "#" cannot be entered. Moving up, down, left or right, return the fewest minutes from the
// top-left cell to the bottom-right cell (the start cell costs nothing), or -1 if there is no way.
// Dijkstra with lazy deletion on numbered cells: cell (r, c) is r * cols + c.
// O(R * C * log(R * C)) time, O(R * C) memory.
import { Heap } from "../heap.ts";

export function cheapestPath(grid: string[]): number {
  const rows = grid.length, cols = rows > 0 ? grid[0].length : 0;
  if (rows === 0 || grid[0][0] === "#" || grid[rows - 1][cols - 1] === "#") return -1;
  const dist = new Float64Array(rows * cols).fill(Infinity);
  const done = new Uint8Array(rows * cols);
  const heap = new Heap<[number, number]>((a, b) => a[0] < b[0]); // [minutes, cell]
  const goal = rows * cols - 1;
  dist[0] = 0;
  heap.push([0, 0]);
  while (heap.size > 0) {
    const [d, cell] = heap.pop()!;
    if (done[cell]) continue; // a stale entry
    if (cell === goal) return d;
    done[cell] = 1;
    const r = Math.floor(cell / cols), c = cell % cols;
    for (const [nr, nc] of [[r - 1, c], [r + 1, c], [r, c - 1], [r, c + 1]]) {
      if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] === "#") continue;
      const next = nr * cols + nc, nd = d + Number(grid[nr][nc]);
      if (nd < dist[next]) {
        dist[next] = nd;
        heap.push([nd, next]);
      }
    }
  }
  return -1;
}

Cost: each of the V = R · C cells has at most 4 edges, so E is at most 4V. Dijkstra with a heap is then O(R · C · log(R · C)) time and O(R · C) memory. The goal’s distance is final when it comes out of the heap, so the loop stops there. slow/cheapest-path.ts scans all cells for the closest one, O((R · C)²), and took 1,676 ms on the last test.

Exercise 4: the cheapest trips (harder)

out and back are flight prices, each sorted from cheapest. A trip is one outbound flight and one return flight. Write cheapestTrips(out, back, k): the k lowest trip prices, cheapest first. Start from exercises/cheapest-trips.ts:

// Exercise 4: `out` and `back` are flight prices, each sorted from cheapest. A trip is one
// outbound flight and one return flight. Returns the k lowest trip prices, cheapest first.
// You may import the Heap from "../heap.ts".
export function cheapestTrips(out: number[], back: number[], k: number): number[] {
  throw new Error("not implemented");
}

For out = [100, 120, 300], back = [40, 70] and k = 3, the answer is [140, 160, 170]. The last test asks for the 100 cheapest of 3,000 × 3,000 trips in under 100 ms.

Hint

For a fixed outbound flight i, the prices out[i] + back[0], out[i] + back[1], and so on are already a sorted list. So the trips are out.length sorted lists, and you need the first k values of their merge. Which lists can hold one of the k cheapest trips?

Solution
// Exercise 4: `out` and `back` are flight prices, each sorted from cheapest. A trip is one
// outbound flight and one return flight. Returns the k lowest trip prices, cheapest first.
// out[i] + back[0], out[i] + back[1], ... is a sorted list for each i, so merge those lists with a
// heap, as mergeSorted does. Only the first min(k, out.length) lists can matter.
// O(k log k) time, O(k) extra memory besides the output.
import { Heap } from "../heap.ts";

export function cheapestTrips(out: number[], back: number[], k: number): number[] {
  const result: number[] = [];
  if (back.length === 0) return result;
  const first: [number, number, number][] = []; // [price, i, j]
  for (let i = 0; i < Math.min(k, out.length); i++) first.push([out[i] + back[0], i, 0]);
  const heap = new Heap<[number, number, number]>((a, b) => a[0] < b[0], first);
  while (result.length < k && heap.size > 0) {
    const [price, i, j] = heap.peek()!;
    result.push(price);
    if (j + 1 < back.length) heap.replaceTop([out[i] + back[j + 1], i, j + 1]); // the next trip in list i
    else heap.pop();
  }
  return result;
}

Cost: at most min(k, n) lists can matter. List i starts at out[i] + back[0], and each list before it starts at that price or lower. So when i ≥ k, k trips at least as cheap already exist.

With n outbound prices, the heap holds one entry per list, built in O(min(k, n)). Each of the k answers costs O(log k), so the total is O(k log k) time and O(k) extra memory, whatever the sizes of out and back. slow/cheapest-trips.ts prices every pair and sorts them, which is O(n · m · log(n · m)) for n outbound and m return prices. It stores all 9,000,000 prices and took 1,001 ms on the last test.

Going deeper

You can skip this section. It covers measurements and internals the main path did not need.

The first runs are slower

A JIT compiler (just-in-time) turns a function that runs often into faster machine code while the program runs. bench.ts runs each function once before timing it, and for topKHeap that’s not enough. warm-up.ts times twelve runs at 250,000 scores in a fresh process:

ms per run: 5.08 6.39 8.03 4.64 0.58 0.52 0.71 0.52 0.60 0.52 0.60 0.52

The first four runs took 5 to 8 ms, then every run took about 0.5 ms. That’s why the first topKHeap row, 6.63 ms, is slower than the second.

How many scores enter the heap

The i-th score is among the top 10 of the first i scores with chance 10/i, when the scores are random and distinct. Adding 10/i over all i gives about k · ln(n/k), where ln is the natural logarithm. replacements.ts counts the calls to replaceTop and prints that estimate next to them:

n=   10,000  replacements   65  k*ln(n/k)   69
n=  100,000  replacements   99  k*ln(n/k)   92
n=1,000,000  replacements  124  k*ln(n/k)  115
n=8,000,000  replacements  132  k*ln(n/k)  136

The worst case for topKHeap

opening-fast.ts also times topKHeap on scores in rising order.

Pause and predict. If the scores arrive in rising order, every score beats the root and costs a full sift down. How long does topKHeap take on 1,000,000 rising scores, against 2.11 ms on random ones?

topKHeap, rising scores
             n   median ms   x prev
       250,000        2.56
       500,000        5.14      2.0
     1,000,000       11.01      2.1

The rising scores took 11.01 ms, about 5 times the random case. That’s the O(n log k) bound paid on every score. It still grew 2 times per doubling, because k stays 10.

What a pair entry costs in memory

memory.ts pushes 1,000,000 items into three heaps and measures each one after a garbage collection. Run it with node --expose-gc memory.ts:

whole numbers      10.5 bytes per entry
fractions          10.4 bytes per entry
[number, number]   74.4 bytes per entry
sizes kept alive: 1000000 1000000 1000000

A whole number or a fraction took about 10.5 bytes: the 8-byte slot plus spare room for the array to grow. A pair took 74.4 bytes, so each two-item array costs about 64 bytes on top of its slot. In dijkstraHeap, the heap can hold one pair per edge, and makeGraph stores each edge as a pair too. At 1,600,000 edges, 64 bytes per pair is about 100 MB.

Node.js uses a heap for its timers

lib/internal/priority_queue.js describes itself as “a basic implementation of a binary heap” (source, v26.13.1). It is 1-based, with the top at heap[1], the first child of pos at pos << 1 and the parent at pos >> 1. Its comparison function returns a number, as sort‘s does.

lib/internal/timers.js keeps one linked list of timers per duration, the lists from Module 4. The heap orders those lists by their expiry time, and by creation order when two expire together (source, v26.13.1). It is an internal module, so your code can’t import it.

Cheat sheet

Figure 10 is the summary of the module: which structure fits which sign in a problem.

sign in the problem                      structure               cost
"top k", "k largest", "k smallest"       heap of size k          O(n log k)
"take the smallest next", again          heap of what waits      O(log n) each
"median so far" after every value        two heaps               O(log n) each
"merge k sorted lists"                   heap, one per list      O(N log k)
"cheapest path", costs differ, none < 0  Dijkstra with a heap    O(E log V)
every item, in order                     sort                    O(n log n)

Figure 10: a heap pays O(log n) to keep only its next item ready, so it wins whenever you need the next few items, not all of them in order.

  • Heap: a complete tree in an array; children of i at 2i + 1 and 2i + 2, parent at (i − 1) >> 1. peek O(1); push, pop, replaceTop O(log n).
  • Top k largest: a min-heap of size k; compare with the root, replaceTop when larger. O(n log k), O(k).
  • All items at the start: build bottom-up in O(n), not n pushes.
  • Running median: a max-heap for the lower half, a min-heap for the upper half, sizes equal or low one larger.
  • Merge k sorted lists: one [value, list, position] entry per list. O(N log k).
  • Cheapest paths, no negative cost: Dijkstra with a min-heap and lazy deletion, O(E log V); the O(V²) scan for dense graphs.
  • Ties: a heap is not stable; add a sequence number when order matters.
  • Next: Module 9 finds items in sorted data with binary search, and makes greedy choices on intervals. One of its exercises imports this module’s heap.

Sources