Module 18
Heaps and Priority Queues
Always know the smallest or largest: how a heap works inside an array, Java's PriorityQueue, top-K, two heaps and K-way merge.
A heap answers one question fast: what is the smallest (or largest) item right now? Adding an item and removing the top both cost O(log n), and peeking at the top is O(1). It does this with a complete binary tree stored inside a plain array.
This module opens the heap up (sift-up and sift-down drawn step by step), then teaches the three heap patterns that cover most interview problems: keep a heap of size K for top-K questions, balance two heaps for running medians, and merge K sorted sources by always taking the smallest head.
Best after: Binary Trees
Part 1
Learn the ideas
- 18.1How a Heap Works Inside an ArrayA min-heap is a complete binary tree where every parent is ≤ its children, stored in an array: the children of index i are 2i + 1 and 2i + 2.15 min
- 18.2PriorityQueue in JavaJava's PriorityQueue is a min-heap by default; pass a Comparator for a max-heap or to order arrays and objects.10 min
- 18.3Top-K: Keep a Heap of Size KTo keep the K largest items, use a min-heap of size K: the top is the weakest of the winners, and anything smaller is thrown out.12 min
- 18.4Two Heaps for a Running MedianA max-heap holds the smaller half and a min-heap the larger half; their tops are the middle values.12 min
- 18.5K-Way MergeMerge K sorted sources by keeping one candidate from each in a min-heap: always take the smallest, then refill from the same source.10 min
Part 2
Solve the problems
In order of difficulty. Each one shows the pattern it teaches.
A max-heap as a simulation tool: repeatedly take the two largest.
K smallest by a computed key: a max-heap of size K keyed on squared distance.
Top-K as a long-lived data structure: the min-heap's top is always the k-th largest.
Greedy with a heap: always run the task with the most copies left; then see the counting formula behind it.
The two-heaps pattern as a class.
Unlock options over time: sorted by requirement, and a max-heap of the options you can currently afford.
Rows as sorted lists: K-way merge, or binary search on the value with a staircase count.
K-way merge with a window: the heap holds one element per list; the range is heap minimum to the running maximum.
Deciding in hindsight: give ladders to the largest climbs so far by keeping them in a min-heap, and pay bricks for the smallest.