Day 7 — Heaps and Priority Queues
Heaps are the data structure that answers a deceptively simple question: “Give me the smallest (or largest) thing right now.” Not the sorted list. Not all of them. Just the one extreme element — fast.
That’s it. That’s the entire job. And once you have an answer to that question in O(log n), an enormous family of problems suddenly has clean solutions.
What you’ll learn today
- Binary heaps — a tree where the parent is always smaller (min-heap) or larger (max-heap) than its children, stored cleverly in a flat array
- The four core operations — push, pop, peek, heapify — and why the array layout makes parent / child lookup arithmetic
- The surprising O(n) build-heap that lets you turn an arbitrary array into a heap faster than sorting it
- Priority queues — the abstract API that languages all expose, backed by a heap underneath
- The two-heap pattern — a max-heap glued to a min-heap that maintains the median of a stream in O(log n)
- Where heaps power real systems — Dijkstra, Huffman coding, A*, event-driven simulation, schedulers
- Ten classic interview problems covering every heap pattern: Kth Largest, Top K Frequent, Merge K Sorted Lists, Median of a Stream, Reorganize String, Task Scheduler, and more
You’ve already met heaps twice. Day 4’s queue variants page introduced priority queues. Day 12’s Heap Sort used a max-heap to sort in place. Today we open the hood and look at what’s actually inside.
Roadmap
- Introduction — what a heap is, the heap property, min vs max, why we store a tree in an array.
- Heap Operations — push, pop, peek, sift-up, sift-down, and the O(n) build-heap.
- Priority Queues — the standard API, plus the stdlib heap in C++, Python, and Java.
- Applications — where heaps actually earn their keep: Dijkstra, Huffman, top-K maintenance, event simulation, scheduling.
- The Two-Heap Pattern — the max-min sandwich that gives you the running median in O(log n).
- Basic Questions — warm-up exercises: verify heap property, trace operations, build heaps by hand.
- Practice Questions — ten interview classics where a heap collapses an O(n log n) problem into something cleaner.
The mental model to keep: a heap is a sorted enough structure — sorted enough to give you the extreme in O(1) and maintain that property in O(log n), but not fully sorted in the middle. That partial-order is where all the speed comes from.