Module 4 · Lesson 1 · ~22 min
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.
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.
Heaps are stored in an array, not as actual node objects. The relationships are indices:
i: parent is (i-1)/2, left child is 2i+1, right child is 2i+2.Watch the bubble dance. Click Push to add values; click Pop to extract the min.
| Operation | Cost | Why |
|---|---|---|
| Peek (top) | O(1) | Always the root. |
| Push | O(log n) | Place at the end, bubble up — depth is log n. |
| Pop | O(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 value | O(n) | No structural ordering between siblings — you have to scan. |
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).
"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
| Problem keyword | Heap move | Big-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 k | O(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 above | O(log n) per insert |
| "Schedule next event" | min-heap of (timestamp, event) | O(log n) per op |
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).