Skip to main content

Heaps & Priority Queues

Learning objectives
  • Explain the array layout of a binary heap and why heap.Init is O(n) while n pushes are O(n log n)
  • Use container/heap correctly (including heap.Fix with index tracking) and write a small generic heap
  • Solve top-k, k-way merge, running median and interval scheduling problems with the right heap shape
  • Connect heaps to real systems: timers, delayed retries, external merge sort, order books, Dijkstra

TL;DR​

  • A binary heap is a complete tree stored in a slice: parent of i is (i−1)/2, children 2i+1 and 2i+2. The root is the min (or max). Push and pop are O(log n); peek is O(1).
  • container/heap works on any type implementing sort.Interface plus Push(any) and Pop() any. Always call the package functions heap.Push / heap.Pop, never your methods directly.
  • Top-k largest: keep a min-heap of size k; the root is the k-th largest. O(n log k) time, O(k) space, works on streams.
  • K-way merge: heap of the current head of each sorted input → O(N log k). This is the merge phase of external sorting for files that do not fit in memory.
  • Running median: max-heap for the lower half, min-heap for the upper half, sizes within one.
  • Updatable priorities: store each item's index and call heap.Fix / heap.Remove — or push duplicates and skip stale entries on pop (lazy deletion).

When to reach for it​

  • "k largest / smallest / most frequent / closest" → heap of size k (or quickselect if one-shot and in memory).
  • "Merge k sorted lists / files / streams" → k-way merge.
  • "Repeatedly take the smallest/largest while new items keep arriving" → priority queue.
  • "Median / percentile of a stream" → two heaps (exact) or a sketch (approximate).
  • "Minimum number of rooms / machines / servers", "schedule tasks by deadline or time" → sort plus a min-heap of end times.
  • Shortest paths with weights, "cheapest", "minimum effort" → Dijkstra (Graphs).
  • Delayed jobs, retries with backoff, timeouts → min-heap keyed by run-at time.

Core concepts​

Array layout, sift up and sift down​

The min-heap above is stored as [2, 5, 3, 9, 7, 4]. The only invariant is parent ≤ children — siblings are unordered, so a heap is not sorted.

  • Push: append at the end, then sift up (swap with the parent while smaller). O(log n).
  • Pop: take the root, move the last element to the root, then sift down (swap with the smaller child while larger). O(log n).
  • Heapify (heap.Init) sifts down every internal node from the bottom up. It is O(n), not O(n log n): half the nodes are leaves needing no work, a quarter move at most one level, an eighth at most two, and the series n·Σ h/2^(h+1) converges to O(n).

container/heap​

// IntHeap is a min-heap of ints implementing heap.Interface.
type IntHeap []int

func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } // flip to > for a max-heap
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
old := *h
n := len(old)
x := old[n-1]
*h = old[:n-1]
return x
}

Your Pop method only removes the last element; heap.Pop first swaps the root to the end, calls your Pop, then restores the invariant. Calling h.Pop() directly returns an arbitrary element — a classic bug.

Updatable priorities with heap.Fix. A scheduler that reschedules jobs (retry with backoff, a cancelled order) needs to change an item already in the heap. Track each item's index in Swap:

type Job struct {
ID string
RunAt time.Time
index int // maintained by JobQueue; required for heap.Fix and heap.Remove
}

type JobQueue []*Job

func (q JobQueue) Len() int { return len(q) }
func (q JobQueue) Less(i, j int) bool { return q[i].RunAt.Before(q[j].RunAt) }
func (q JobQueue) Swap(i, j int) {
q[i], q[j] = q[j], q[i]
q[i].index = i
q[j].index = j
}

func (q *JobQueue) Push(x any) {
j := x.(*Job)
j.index = len(*q)
*q = append(*q, j)
}

func (q *JobQueue) Pop() any {
old := *q
n := len(old)
j := old[n-1]
old[n-1] = nil // do not retain the pointer
j.index = -1
*q = old[:n-1]
return j
}

// Reschedule moves a queued job to a new time in O(log n).
func (q *JobQueue) Reschedule(j *Job, at time.Time) {
j.RunAt = at
heap.Fix(q, j.index)
}

heap.Remove(q, j.index) cancels a job in O(log n). The alternative, lazy deletion, pushes a new entry and marks the old one stale, skipping stale entries when they reach the top — simpler, but the heap can fill with garbage under heavy churn.

A generic heap​

container/heap predates generics, so every element passes through any. A small generic heap avoids the boxing and the boilerplate; the rest of this page uses it.

// Heap is a binary heap ordered by less (a min-heap when less is "<").
type Heap[T any] struct {
items []T
less func(a, b T) bool
}

func NewHeap[T any](less func(a, b T) bool) *Heap[T] { return &Heap[T]{less: less} }

func (h *Heap[T]) Len() int { return len(h.items) }

// Peek returns the top element; it panics if the heap is empty.
func (h *Heap[T]) Peek() T { return h.items[0] }

func (h *Heap[T]) Push(v T) {
h.items = append(h.items, v)
h.up(len(h.items) - 1)
}

// Pop removes and returns the top element; it panics if the heap is empty.
func (h *Heap[T]) Pop() T {
n := len(h.items) - 1
top := h.items[0]
h.items[0] = h.items[n]
var zero T
h.items[n] = zero
h.items = h.items[:n]
if n > 0 {
h.down(0)
}
return top
}

func (h *Heap[T]) up(i int) {
for i > 0 {
parent := (i - 1) / 2
if !h.less(h.items[i], h.items[parent]) {
return
}
h.items[i], h.items[parent] = h.items[parent], h.items[i]
i = parent
}
}

func (h *Heap[T]) down(i int) {
n := len(h.items)
for {
best := i
if l := 2*i + 1; l < n && h.less(h.items[l], h.items[best]) {
best = l
}
if r := 2*i + 2; r < n && h.less(h.items[r], h.items[best]) {
best = r
}
if best == i {
return
}
h.items[i], h.items[best] = h.items[best], h.items[i]
i = best
}
}

Where heaps live in real systems​

  • Timers: the Go runtime keeps timers in a 4-ary heap (wider and shallower than binary, fewer cache misses); time.AfterFunc, context.WithTimeout and HTTP deadlines all land there.
  • Delayed retries and scheduled jobs: webhook redelivery, payment retry with exponential backoff, "release the inventory hold after 15 minutes" — a min-heap keyed by run-at time, or the distributed equivalent (a Redis sorted set scored by timestamp, delayed queues in a broker — see Message Queues & Event Streaming).
  • External merge sort: sort chunks that fit in memory, write them as runs, then k-way merge the runs with a heap — how you reconcile two 50 GB settlement files on a 4 GB machine (Reconciliation & Settlement).
  • Order books: best bid is a max over buy prices, best ask a min over sell prices. A heap gives top-of-book in O(1), but cancellations in the middle are frequent, so matching engines usually keep price levels in an ordered map or array with a FIFO queue per level (Stock Exchange).
  • Schedulers: priority-based CPU and job schedulers (CPU Scheduling), Dijkstra and A* in routing.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Binary heapO(log n) push/pop, O(1) peek, compact sliceNo ordered iteration; arbitrary search is O(n)Repeated min/max extraction with inserts
d-ary heap (e.g. 4-ary)Shallower, cache-friendlier, faster pushSlower pop (more children to compare)Push-heavy workloads such as timers
Sorted sliceO(1) min/max, ordered iterationO(n) insertFew inserts, many reads
Balanced BST / ordered mapMin, max, delete-any, range in O(log n)Pointer-heavy, more code (no stdlib type in Go)Frequent cancellations, need ordered iteration
QuickselectO(n) average for a one-shot k-th elementO(n²) worst case, needs all data in memory, mutatesOne-off k-th / top-k on a slice
Bucket countingO(n) top-k by frequencyNeeds bounded countsTop-k frequent with frequency ≤ n
Count-min sketch + heapApproximate heavy hitters in tiny memoryOverestimatesUnbounded streams (Data Structures Inside Real Systems)

In practice​

Problem 1 — Kth Largest Element in an Array (LeetCode 215)​

Problem. Return the k-th largest value in an unsorted slice.

Approach. Min-heap of size k: fill it with the first k values; after that, a new value that beats the root replaces it. The heap always holds the k largest values seen so far, so its root is the answer. It works on a stream and needs only O(k) memory. Quickselect is O(n) on average if the data is already in memory.

func findKthLargest(nums []int, k int) int {
h := make(IntHeap, 0, k+1)
for _, v := range nums {
if h.Len() < k {
heap.Push(&h, v)
} else if v > h[0] {
h[0] = v // replace the smallest of the top k
heap.Fix(&h, 0)
}
}
return h[0]
}

Complexity. O(n log k) time, O(k) space. Replacing the root and calling heap.Fix does one sift instead of a push plus a pop.

Problem 2 — Merge k Sorted Lists (LeetCode 23)​

Problem. Merge k sorted linked lists into one sorted list.

Approach. Put the head of each list in a min-heap; repeatedly pop the smallest, append it, and push its successor. The heap never holds more than k nodes.

type ListNode struct {
Val int
Next *ListNode
}

func mergeKLists(lists []*ListNode) *ListNode {
h := NewHeap(func(a, b *ListNode) bool { return a.Val < b.Val })
for _, l := range lists {
if l != nil {
h.Push(l)
}
}
dummy := &ListNode{}
tail := dummy
for h.Len() > 0 {
n := h.Pop()
tail.Next = n
tail = n
if n.Next != nil {
h.Push(n.Next)
}
}
return dummy.Next
}

Complexity. O(N log k) for N total nodes, O(k) heap space. Divide-and-conquer pairwise merging has the same bound with no heap. Replace "list" with "sorted run file" and you have the merge phase of external sorting.

Problem 3 — Find Median from Data Stream (LeetCode 295)​

Problem. Support Add(num) and Median() over a growing stream.

Approach. low is a max-heap holding the smaller half; high is a min-heap holding the larger half. Route every new value through low into high so the halves stay ordered, then rebalance so low has the same size as high or one more. The median is low's top, or the mean of both tops.

type MedianFinder struct {
low *Heap[int] // max-heap: smaller half
high *Heap[int] // min-heap: larger half
}

func NewMedianFinder() *MedianFinder {
return &MedianFinder{
low: NewHeap(func(a, b int) bool { return a > b }),
high: NewHeap(func(a, b int) bool { return a < b }),
}
}

func (m *MedianFinder) Add(v int) {
m.low.Push(v)
m.high.Push(m.low.Pop()) // the largest of the low half moves up
if m.high.Len() > m.low.Len() {
m.low.Push(m.high.Pop())
}
}

// Median panics if no values were added.
func (m *MedianFinder) Median() float64 {
if m.low.Len() > m.high.Len() {
return float64(m.low.Peek())
}
return float64(m.low.Peek()+m.high.Peek()) / 2
}

Complexity. Add O(log n), Median O(1), O(n) space. For p99 latency over millions of requests, exact heaps are too big — use histograms or sketches (HDRHistogram, t-digest) as in Observability & SLOs.

Problem 4 — Meeting Rooms II (LeetCode 253)​

Problem. Given meeting intervals [start, end), find the minimum number of rooms needed.

Approach. Sort by start time. Keep a min-heap of end times for rooms in use. For each meeting, if the earliest-ending room is free by its start, reuse it (pop); then push this meeting's end. The heap size is the number of rooms.

func minMeetingRooms(intervals [][2]int) int {
sorted := slices.Clone(intervals)
slices.SortFunc(sorted, func(a, b [2]int) int { return cmp.Compare(a[0], b[0]) })
ends := NewHeap(func(a, b int) bool { return a < b }) // end times of rooms in use
for _, iv := range sorted {
if ends.Len() > 0 && ends.Peek() <= iv[0] {
ends.Pop() // the earliest-ending room is free again
}
ends.Push(iv[1])
}
return ends.Len()
}

Complexity. O(n log n) time, O(n) space. The same shape answers "how many payment workers are needed so no job waits" or "peak concurrent sessions"; a sweep line over sorted start/end events gives the same count without a heap.

Practice list​

  • Easy: Kth Largest Element in a Stream (703), Last Stone Weight (1046)
  • Medium: Kth Largest Element in an Array (215), Top K Frequent Elements (347), K Closest Points to Origin (973), Task Scheduler (621), Meeting Rooms II (253), Reorganize String (767), Design Twitter (355), Single-Threaded CPU (1834)
  • Hard: Merge k Sorted Lists (23), Find Median from Data Stream (295), IPO (502), Sliding Window Median (480)

Common pitfalls​

  • Calling h.Pop() instead of heap.Pop(&h). Your method removes the last slice element, not the minimum. Symptom: "random" results.
  • Building the slice by hand and forgetting heap.Init. The invariant does not hold until you call it.
  • Max-heap by negating values overflows for math.MinInt; flip Less instead.
  • No tie-breaker. Heaps are not stable: equal priorities pop in arbitrary order. For fairness (FIFO among equal priorities, price-time priority in matching) add a monotonically increasing sequence number to the comparison.
  • Peeking an empty heap (h[0]) panics — check Len first.
  • Lazy deletion without bounds: stale entries accumulate when priorities change often. Symptom: heap size far larger than the number of live items, rising memory.
  • Using a heap when you need ordered iteration or range queries — a heap only gives you the top.
  • Distributed top-k done wrong: taking the top-k from each shard and merging is exact only if each key lives on exactly one shard. If counts for the same key are split across shards, partition by key first or accept an approximation.

Interview angle​

  • Name the shape quickly: "k largest → min-heap of size k, O(n log k)". Then volunteer alternatives (quickselect O(n) average; bucket sort for frequencies) and when each wins.
  • Explain why the heap for largest is a min-heap — interviewers check this.
  • Go specifics they notice: correct container/heap usage, pointer receivers for Push/Pop, heap.Fix for updates, or a clean generic heap.
  • Follow-ups: "The stream is unbounded and has 100M distinct keys" (count-min sketch + small heap), "Merge 1,000 sorted files of 1 GB each" (external merge with buffered readers, k-way heap), "Jobs can be rescheduled or cancelled" (indexed heap), "Make it distributed" (Redis sorted set scored by time; partition by key).
  • Red flags: sorting everything for top-k on a stream, or not knowing that heapify is O(n).

Self-check​

1. Why is the k-th largest element found with a min-heap rather than a max-heap?

You keep only the k largest values seen so far and need to evict the smallest of them whenever a bigger value arrives. A min-heap of size k gives O(1) access to that smallest element (the root), which is exactly the k-th largest overall. A max-heap would require holding all n values.

2. Why is heap.Init O(n) when n pushes are O(n log n)?

Init sifts down from the bottom up. Most nodes are near the bottom and can move only a few levels: n/2 leaves move zero, n/4 move at most one, n/8 at most two, and so on. The total n·Σ h/2^(h+1) is bounded by a constant times n. Pushes sift up from the bottom, and each of the many late pushes can travel the full height log n.

3. What is the difference between your Pop method and heap.Pop in container/heap?

heap.Pop swaps the root with the last element, calls your Pop to remove the last element (now the old root), and then sifts the new root down. Your Pop must only remove and return the last slice element. Calling it directly skips the swap and the sift.

4. How do you change the priority of an item that is already in a container/heap?

Keep the item's current index inside the item, updated in Swap and Push. After changing the priority, call heap.Fix(h, item.index) to sift it up or down in O(log n). heap.Remove(h, item.index) deletes it. Alternatively use lazy deletion: push a new entry and skip outdated ones when popped.

5. How does the two-heap median keep both operations fast?

All values in the max-heap (lower half) are ≤ all values in the min-heap (upper half), and their sizes differ by at most one. The median is therefore at one or both roots, readable in O(1). Each insert does a constant number of pushes/pops to restore the size and order invariants: O(log n).

6. Scenario: you must reconcile two 40 GB settlement files sorted by transaction ID on a machine with 4 GB of RAM. How do you do it, and if the files are not sorted?

If sorted, stream both files with buffered readers and do a two-way merge-compare (two pointers) — O(n) time, O(1) memory. If unsorted, external sort each: read 2–3 GB chunks, sort in memory, write sorted runs, then k-way merge the runs with a min-heap of run heads, then merge-compare. Make it restartable (checkpoint run files) and verify record counts and totals per run.

7. Why might a matching engine not use a plain binary heap for its order book?

Orders at a price level are matched FIFO (price-time priority) and cancellations hit arbitrary orders frequently. A plain heap gives the best price fast but cancellation needs O(n) search or index tracking, and it does not support walking price levels in order. Ordered maps or arrays of price levels, each with a FIFO queue and an order-ID index, fit better.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Build a delayed-retry scheduler for outbound payment webhooks:

  1. Scheduler with Schedule(job, at), Cancel(id), and Reschedule(id, at), backed by JobQueue plus a map[string]*Job index.
  2. A run loop that sleeps on a time.Timer until the earliest RunAt, wakes early when a sooner job is scheduled, and executes due jobs; failures are rescheduled with exponential backoff and jitter, capped at 5 attempts.
  3. Inject a clock interface so tests are deterministic.

Done when tests cover ordering, cancellation, rescheduling to an earlier time, and backoff caps; the scheduler passes -race; and you can explain how you would move it to a Redis sorted set for multiple replicas without double delivery.

Further reading​

  • Go documentation: container/heap (including its PriorityQueue example with heap.Fix)
  • Introduction to Algorithms (CLRS) — heapsort and priority queues chapter
  • Sedgewick & Wayne, Algorithms, 4th ed. — priority queues and index priority queues
  • Go source: runtime/time.go — the runtime timer heap
  • Martin Kleppmann, Designing Data-Intensive Applications — sorting and merging in batch processing
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).