Heaps & priority queues

Top-K, k-way merge, two-heap median. Know why heapify is O(n) and when a heap beats sorting.

About 32 min read3-question knowledge check

The mental model

A heap is a triage nurse. Patients arrive in any order — a sprained ankle, a heart attack, a headache — and the nurse does not sort the whole waiting room. She only guarantees one thing: *the most urgent person is always seen next.* She does not care about the exact order of everyone else, and she does not need to. Adding a new patient or pulling the most urgent one takes a quick reshuffle, not a full re-sort. That is precisely what a heap gives you: instant access to the min or max, cheap insertion, cheap removal of that extreme — and deliberately no ordering of anything else.

A priority queue is the *abstract* idea — "give me the highest-priority item next" — and a heap is the usual *implementation* of it. The distinction matters in interviews: the priority queue is the interface (push, pop-min), the heap is the data structure (a nearly-complete binary tree with the heap property) that makes that interface fast.

Why does this exist? Because a specific question comes up constantly: "what is the current best/worst, and let me keep adding and removing as I go?" A sorted array answers "what is the best" in O(1) but costs O(n) to insert into. A hash map inserts in O(1) but cannot tell you the minimum without scanning everything. A balanced BST does both in O(log n) but is heavier and gives you full ordering you often do not need. The heap is the minimal structure that does exactly the three operations you actually want — peek-extreme in O(1), push in O(log n), pop-extreme in O(log n) — by refusing to maintain any order it does not have to.

The interview payoff is a family of problems that all reduce to "maintain a running set of candidates and always know the extreme": top-K (keep a heap of size k), k-way merge (a heap of the current fronts), running median (two heaps balanced against each other), Dijkstra and Prim (always expand the cheapest frontier edge), and event scheduling (always process the earliest event). Recognizing the "always want the current extreme" shape and reaching for a heap is the reusable move. The two facts that separate a strong answer: building a heap from n items is O(n), not O(n log n), and a size-k heap beats sorting when you only need the top k — both explained below.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision