Chapter 11 · Trees

Priority Queues

A regular queue serves people in order of arrival. A priority queue serves the most urgent task next — regardless of when it arrived. It is the abstract data type that heaps were invented to implement.

What is a priority queue?

A priority queue always gives you the highest-priority (or lowest-value) item next, not the oldest. It's usually implemented with a binary heap, which makes insert and remove-top O(log n) and peeking O(1). Priority queues drive Dijkstra's shortest path, task schedulers, event simulations and "top K" problems.

// Minimal min-priority queue using a binary heap
class MinPQ {
  h = [];
  push(x) { this.h.push(x); let i = this.h.length - 1;
    while (i && this.h[(i - 1) >> 1] > this.h[i]) { [this.h[i], this.h[(i - 1) >> 1]] = [this.h[(i - 1) >> 1], this.h[i]]; i = (i - 1) >> 1; } }
  pop() { const top = this.h[0], last = this.h.pop();
    if (this.h.length) { this.h[0] = last; let i = 0;
      for (;;) { let s = i, l = 2 * i + 1, r = l + 1;
        if (this.h[l] < this.h[s]) s = l; if (this.h[r] < this.h[s]) s = r;
        if (s === i) break; [this.h[i], this.h[s]] = [this.h[s], this.h[i]]; i = s; } }
    return top; }
}

Visualizing a min-priority queue

Tasks inserted in random order — always extracted by lowest priority number first:

1
Send alert emailnext dequeue
2
Process payment
3
Update database
5
Generate report
7
Log audit trail
🔍ADT vs implementation
Priority Queue is an abstract data type (ADT) — a specification of behavior. A heap is one implementation. You could also use a sorted array or an unsorted array, but only a heap gives you O(log n) for both insert and extract-min.

Live demo — min priority queue

Insert values with implicit priorities and watch the min-heap maintain the invariant. Extract-min always removes the smallest element in O(log n).

Min-Heap — parent ≤ children always

min = 1 · size = 6
1531087
root (min)bubble-up pathextracted min
arr:
1
[0]
5
[1]
3
[2]
10
[3]
8
[4]
7
[5]

Priority queue interface

priority-queue.pseudo
1PriorityQueue (min-heap implementation):
2 
3insert(value, priority):
4 // Wrap value with its priority
5 node <- { value, priority }
6 heap.push(node) // append to heap
7 siftUp(heap, heap.size - 1) // restore min-heap property
8 // O(log n)
9 
10extractMin():
11 if heap is empty: error
12 min <- heap[0].value // root has smallest priority
13 heap[0] <- heap[last]
14 heap.removeLast()
15 siftDown(heap, 0) // restore min-heap property
16 return min
17 // O(log n)
18 
19peek():
20 return heap[0].value // O(1)
21 
22decreaseKey(node, newPriority): // used in Dijkstra
23 node.priority <- newPriority
24 siftUp(heap, node.index) // move up — priority got smaller
25 // O(log n)

Implementations compared

ImplementationinsertextractMinpeek
Unsorted arrayO(1)O(n)O(n)
Sorted arrayO(n)O(1)O(1)
★ Binary heapO(log n)O(log n)O(1)
★ Fibonacci heapO(1) amort.O(log n)O(1)

Where priority queues show up

Dijkstra's algorithm

Extract the nearest unvisited vertex at each step. A min-heap makes each extraction O(log n).

A* pathfinding

Always expand the node with the lowest estimated total cost. Used in GPS navigation and game AI.

OS task scheduler

The CPU always runs the highest-priority ready process. Interrupts are priority-queue events.

Merge k sorted lists

Insert the head of each list. Extract min, advance that list, re-insert. O(n log k) total.

Event-driven simulation

Events scheduled by timestamp. Always process the next-in-time event using a min-heap.

Huffman coding

Repeatedly merge the two lowest-frequency symbols. A min-heap gives O(n log n) Huffman tree build.

Time complexity

peek (min or max) — root is always optimalO(1)

Constant time

insert — sift up at most height levelsO(log n)

Logarithmic time

extractMin / extractMax — sift down after removalO(log n)

Logarithmic time

decreaseKey — used in Dijkstra's algorithmO(log n)

Logarithmic time

🎯 Quick Check

You need to repeatedly extract the smallest element from a dynamic set where new elements are also added. Which is the best data structure?

🧠Remember: heap = priority queue implementation
When you hear “use a priority queue for this problem,” mentally translate it to “use a heap.” Every serious algorithm that processes elements in priority order — Dijkstra, Prim, Huffman, A* — uses a heap internally.

Priority Queues: summary

Key points

  • Sorting the whole array to get the minimum each time is O(n log n); a heap gives O(log n) per operation.
  • To find the top K largest items, keep a min-heap of size K: O(n log K).
  • JavaScript has no built-in priority queue; write a heap or use a small library.

Frequently asked questions

›Is a priority queue the same as a heap?

A priority queue is the abstract behaviour (get the best item next); a heap is the most common way to implement it.