Module 4 · Lesson 1 · ~22 min

Heaps, the bubble dance, and top-K

A heap is the "I always need the smallest (or largest) thing right now" data structure. Once you internalize the shape and the bubble dance, an entire family of "top-K" problems becomes free.

The metaphor: a tournament bracket that always knows the winner

Picture a single-elimination tournament bracket. The bracket is shaped like a tree where every parent's value is the winner of its two children. The root is always the overall winner. When the winner leaves (you "pop the heap"), the bracket reorganizes — losers bubble up and lose again until a new champion sits at the top.

That's a heap. It's a complete binary tree with the property: every parent is "better" (smaller, in a min-heap) than its children. Inserts and pops are O(log n) because they only walk one path from root to leaf.

The metaphor

A heap is a tournament that re-runs the final whenever the champion graduates. The next-best contender bubbles up automatically.

The shape — array-backed

Heaps are stored in an array, not as actual node objects. The relationships are indices:

Watch the bubble dance. Click Push to add values; click Pop to extract the min.

Big-O

OperationCostWhy
Peek (top)O(1)Always the root.
PushO(log n)Place at the end, bubble up — depth is log n.
PopO(log n)Move last to root, bubble down — depth is log n.
Heapify (build from array)O(n)Counterintuitive — most nodes are near the leaves with short bubble distances. The total work sums to O(n).
Search for arbitrary valueO(n)No structural ordering between siblings — you have to scan.
The O(n) heapify trick

If you have all your data upfront, building a heap from a list is O(n), not O(n log n). You bubble down from the bottom-up. Most nodes are near the leaves and have nowhere to bubble. The math works out to O(n). In Python: heapq.heapify(arr).

Top-K — the killer use case

"Find the k largest elements in a stream of n." Brute force: sort all of n at O(n log n). Smarter: maintain a min-heap of size k. For each new element, if it's larger than the current minimum, replace the minimum.

Total work: O(n log k). When k ≪ n, this is dramatically faster than the sort.

import heapq

def top_k(nums, k):
    h = []
    for x in nums:
        if len(h) < k:
            heapq.heappush(h, x)
        elif x > h[0]:
            heapq.heapreplace(h, x)
    return sorted(h, reverse=True)
# O(n log k) time, O(k) space
// JS has no built-in heap; see the MinHeap class in tools/reference.html
function topK(nums, k) {
  const h = new MinHeap();
  for (const x of nums) {
    if (h.size < k) h.push(x);
    else if (x > h.peek()) { h.pop(); h.push(x); }
  }
  const out = [];
  while (h.size) out.push(h.pop());
  return out.reverse();
}
// O(n log k) time, O(k) space
function topK(nums: number[], k: number): number[] {
  const h = new MinHeap<number>();
  for (const x of nums) {
    if (h.size < k) h.push(x);
    else if (x > h.peek()!) { h.pop(); h.push(x); }
  }
  const out: number[] = [];
  while (h.size) out.push(h.pop()!);
  return out.reverse();
}
// O(n log k) time, O(k) space

The pattern recognizer

Problem keywordHeap moveBig-O
"Top K largest / smallest"min-heap of size k (for largest)O(n log k)
"K most frequent"frequency map → min-heap of size kO(n log k)
"Merge K sorted lists"min-heap of (value, list-id, index)O(N log k) where N = total
"Median from a stream"two heaps — max-heap below median, min-heap aboveO(log n) per insert
"Schedule next event"min-heap of (timestamp, event)O(log n) per op

Python heapq is a min-heap. JavaScript has none.

Annoying detail. Python's heapq implements a min-heap. To get a max-heap, push the negation of your values. JavaScript has no built-in heap — for interview problems you either implement one or simulate with a sorted insertion (acceptable for very small k).

Try it