← Heaps · guided lesson
Heaps & Priority Queues
the story
Binary heap: sift up and sift down
Every tool here exists because something was too slow or broke without it. Here is what.
The binary heap arrived in June 1964, inside J. W. J. Williams's Algorithm 232: Heapsort in Communications of the ACM.
It keeps a tree in a plain array with a single rule — every parent ≤ its children — so the minimum is always the first element (A[1] in his ALGOL, index 0 in Java).
The Java Toolkit chapter's PriorityQueue card tells how this structure became java.util.PriorityQueue in Java 5.
This card is about the two moves that make it work: sift up and sift down.
the problem it solved
Taking the smallest item again and again while new items keep arriving — O(log n) per step instead of re-sorting everything.
why it matters: without it
"Give me the next most urgent item" would mean a full scan or a re-sort on every call — O(n) or O(n log n) instead of O(log n).
sources: J. W. J. Williams, Algorithm 232: Heapsort, Communications of the ACM 7(6), 1964 ↗ · OpenJDK 17 source: java.util.PriorityQueue ("represented as a balanced binary heap") ↗
also in this chapter: Building a heap in O(n) (Floyd's heapify) · Heapsort · Top-k with a size-k heap · Two heaps for a running median · K-way merge with a min-heap · Greedy with a heap
the idea
The idea in 30 seconds
A heap is a complete binary tree where every parent is ≤ its children (min-heap). So the minimum is always on top.
It isn't fully sorted — only parent vs child is ordered. That weaker promise is what makes insert and remove-min cheap: O(log n).
It lives in a plain array: the children of index i are 2i+1 and 2i+2, the parent is (i−1)/2. Java's PriorityQueue is exactly this.
picture this
Think of the scheduler behind Task Manager: dozens of processes are waiting, and the CPU always picks the most urgent one next. When a new process arrives, it is slotted in with a few comparisons — nobody re-sorts the whole waiting list.
watch it
offer — append and sift up
Predict mode is on. Before each step, guess what happens, then watch. Wrong guesses are fine; that is how it sinks in.
offer — append and sift up
Tree and array are the same data. Watch a value bubble up while it's smaller than its parent at (i−1)/2.
On this screen ← / → step the simulation. Use the buttons below to move through the lesson.
watch it
poll — take the root, sift down
Predict mode is on. Before each step, guess what happens, then watch. Wrong guesses are fine; that is how it sinks in.
poll — take the root, sift down
The last leaf jumps to the root to keep the tree complete, then sinks past the smaller child.
On this screen ← / → step the simulation. Use the buttons below to move through the lesson.
key idea 1 of 9
Read it once. Say it out loud once. Bas.
Heap property: min-heap → every parent ≤ its children (max-heap: ≥). Siblings have no order, so the array is not sorted.
key idea 2 of 9
Read it once. Say it out loud once. Bas.
Shape property: the tree is complete — every level full except the last, which fills left to right. That's why it fits in an array with no gaps and has height ⌊log₂ n⌋.
key idea 3 of 9
Read it once. Say it out loud once. Bas.
Index math (0-based): parent(i) = (i − 1) / 2, left(i) = 2i + 1, right(i) = 2i + 2.
key idea 4 of 9
Read it once. Say it out loud once. Bas.
offer = append + sift up: swap with the parent while smaller. poll = take root, move the last leaf to the root, sift down: swap with the smaller child while bigger. Both walk one path: O(log n). peek is O(1).
key idea 5 of 9
Read it once. Say it out loud once. Bas.
Build a heap in O(n) (heapify): sift down every parent from the last one up to the root. Most nodes are near the bottom and barely move, so the total work is linear — not n log n.
key idea 6 of 9
Read it once. Say it out loud once. Bas.
`PriorityQueue` is a min-heap by default. Max-heap: new PriorityQueue<>(Comparator.reverseOrder()). remove(Object) and contains are O(n) — a heap can't find an arbitrary element fast.
key idea 7 of 9
Read it once. Say it out loud once. Bas.
Top-k pattern: k largest → keep a min-heap of size k (the root is the weakest of the winners and gets kicked out). k smallest → max-heap of size k. O(n log k).
key idea 8 of 9
Read it once. Say it out loud once. Bas.
Two heaps (max-heap for the lower half, min-heap for the upper half) give a running median; k-way merge keeps one cursor per sorted list in a heap — also for "rows" you never build, like the sum table in Find K Pairs.
key idea 9 of 9
Read it once. Say it out loud once. Bas.
Greedy with a heap: keep the candidates in a heap and act on the best one now (heaviest stone, biggest affordable profit). When candidates unlock over time, sort them by the unlock key once and push them in as they unlock.
spot the pattern
When you see this, think this
"k largest", "k smallest", "k closest", "top k frequent"
Size-k heap in the opposite direction (or quickselect / buckets)
"kth largest in a stream", values keep arriving
Size-k min-heap; the root is the answer
"median" of a changing collection
Two heaps, sizes balanced within one
Merge k sorted things
Min-heap of (value, source, index) cursors
+6 more signals on the chapter page
watch out
A trap or two
Many wrong answers in interviews come from small slips like these, not from the hard part.
- Expecting
PriorityQueueto iterate or print in sorted order — onlypollgives sorted order. - Comparator
(a, b) -> a - boverflows (e.g.Integer.MIN_VALUE - 1). UseInteger.compare(a, b)orComparator.comparingInt.
quick check
One question. No pressure.
In a 0-indexed array heap, where are the children of index 4?
now try
Your first real problem
You know enough to try this one. Stuck? Use the hints; that is what they are for.
Kth Largest Element in a Stream
open the problem →recall
Flip a few cards
Answer in your head first, then flip. Grade yourself honestly; the schedule brings back what you forget.
In a 0-indexed array heap, where are the parent and the children of index i?
Question 1: In a 0-indexed array heap, where are the parent and the children of index i?
done
Lesson complete
Chalo, that is the core. The full chapter has the rest: cost tables, Java details and more problems.