The Efficient Priority Queue
Use arrow keys or buttons to navigate
A complete binary tree with a special ordering property
A heap is not a fully sorted structure. It only guarantees the root is the min (or max). Left child is not necessarily smaller than right child. This partial ordering is what makes heaps fast.
The CEO (root) always has the lowest employee ID. Every manager's ID is lower than their reports. Finding the CEO is instant — just look at the top!
The three properties that make heaps work
All levels full except possibly the last, filled left to right.
Min-heap: parent ≤ children
Max-heap: parent ≥ children
Complete tree → always balanced → height = floor(log₂ n).
Every operation that travels root-to-leaf (or vice versa) costs at most O(log n). With n = 1,000,000, that's only ~20 steps instead of 1,000,000.
The best of both worlds for priority queue operations
| Implementation | insert | removeMin |
|---|---|---|
| Unsorted List | O(1) | O(n) |
| Sorted List | O(n) | O(1) |
| Heap | O(log n) | O(log n) |
A heap gives O(log n) for both operations. With n = 1,000,000, that's ~20 steps instead of 1,000,000. This makes heaps the go-to PQ implementation.
insert: add at bottom, bubble UP → O(log n)
removeMin: swap root with last, bubble DOWN → O(log n)
Both travel at most the height of the tree.
No pointers needed — store a heap in a simple array!
Hover over any node or array cell to highlight both
Because the tree is complete, there are no gaps when we lay it out level by level. A flat array with zero wasted space — no left/right child pointers needed!
Fill seats row by row, left to right, no empty seats. Seat number alone tells you the row and position — exactly how a heap fits in an array.
Navigate the tree using simple arithmetic — no pointers!
Parent uses integer division (floor). Both index 1 and 2 map to parent 0: (1-1)/2 = 0 and (2-1)/2 = 0.
Add at the end, then swim the element up to restore heap order
Worst case: bubble all the way to root. Distance = height = O(log n). Each swap is O(1).
Joins at the bottom. If they outrank their manager (smaller key), they swap. Keep promoting until they meet someone who outranks them.
Step-by-step trace with code sync
Element 2 bubbled up one level. Only 1 swap because 2 > 1 (the root). Worst case: an element could bubble all the way to root — O(log n) swaps.
Adding at the end always keeps the tree complete. The bubble-up only affects the order, never the shape.
Remove root, move last to root, then sink it down
Swapping with the larger child would make it the parent of the smaller child — violating heap order! Always pick the smaller child in a min-heap.
Step-by-step trace of removing the minimum
Moving the last element to root preserves completeness. Bubble-down restores heap order. Two properties, two steps, O(log n).
The CEO retires. The most junior employee is temporarily placed at the top. They then get demoted level by level until they find their proper rank.
Insert elements one at a time — O(n log n)
Each insert is O(log n) worst case. Doing n inserts → O(n log n) total.
Yes! The bottom-up approach builds a heap in O(n). The key insight: start from the leaves and sift down, not from the root and sift up.
Later inserts (when the heap is big) bubble up a long distance. Most of the work happens when it's most expensive.
Start from the last internal node and sift down — O(n)!
Process from the last internal node up to root. Each node sifts down at most to the bottom.
Leaves (half the nodes) do zero work. A quarter sift 1 level. Only the root sifts h levels. The work is concentrated where it's cheapest!
Most nodes are near the bottom and barely need to move
n/2 leaves → sift 0 levels (skip!)
n/4 nodes → sift at most 1 level
n/8 nodes → sift at most 2 levels
...
1 node (root) → sift at most h levels
Top-down = O(n log n) — the many late inserts bubble up a long distance.
Bottom-up = O(n) — the many bottom nodes sift a short distance. Work is concentrated where it's cheapest.
Top-down: training each new employee from scratch. Bottom-up: reorganizing an existing company — most people barely move, only the top executives shuffle significantly.
Build a max-heap, then repeatedly extract the maximum — O(n log n), in-place!
We want ascending order. Extract max and place at end → sorted region grows right-to-left. Heap shrinks, sorted part grows.
Time: O(n log n) always
Space: O(1) — in-place!
Stable: No
Quicksort is faster in practice but O(n²) worst case. Merge sort is stable but needs O(n) extra space.
Sort [5, 3, 8, 1, 4, 2] step by step using max-heap extraction
Each extract-max places the largest remaining element at the end. The sorted region grows from right to left. Total: O(n log n), in-place, not stable.
Same structure, just flip the comparison operator
removeMin() returns smallestJava's PriorityQueue = min-heap by default
removeMax() returns largestUse Collections.reverseOrder() comparator
The only difference is the direction of the comparison. All algorithms (insert, remove, heapify) are structurally identical — just swap < with >. Think of them as the same data structure with a configurable comparator.
Predict the state after a sequence of operations
Starting with an empty min-heap, perform these operations:
What is the array representation of the heap after all operations?
After insert(5,3,8,1): [1,3,8,5]. removeMin→removes 1: [3,5,8]. insert(2): [2,5,8,3]. removeMin→removes 2: [3,5,8].
Built-in min-heap — ready to use
| Method | Description | Time |
|---|---|---|
add(e) | Insert | O(log n) |
peek() | View min | O(1) |
poll() | Remove min | O(log n) |
size() | Count | O(1) |
Java's PriorityQueue is a min-heap by default. If you need the largest first, you must provide a reversed comparator!
This bottom-up heapify has a subtle bug. Can you spot it?
n/2 - 1. Starting at n/2 wastes one iteration on a leaf node — or worse, causes an ArrayIndexOutOfBoundsException when n is odd. The fix: for (int i = n/2 - 1; i >= 0; i--)
Find the k largest elements using a min-heap of size k
Process n elements, each heap op is O(log k). For k=10 and n=1 billion, that's ~33 ops per element instead of sorting everything. The heap root always holds the smallest of the k largest — the gatekeeper.
Min-heap or max-heap? Match each scenario to the correct choice.
1. Find the 3 smallest elements in a stream of 1 million numbers.
2. Find the 5 largest elements in a stream.
3. Sort an array in ascending order using heap sort.
4. Implement a task scheduler where lowest priority number = highest urgency.
1. Min-heap: Keep the 3 smallest. Root = largest of the 3. If new element < root, evict root and insert. (Wait — this is tricky! For smallest-K, use a max-heap as gatekeeper. But the question says "min-heap of size 3" which would keep the smallest 3 if you evict the min when you see a smaller one... Actually: to find K smallest, use a max-heap of size K. The root is the largest of the K smallest — the gatekeeper.)
Gotcha! Q1 is a trick — the correct answer is actually max-heap! The gatekeeper must be the opposite type. For top-K largest → min-heap. For bottom-K smallest → max-heap.
2. Min-heap: Root = smallest of the 5 largest = gatekeeper. Correct!
3. Max-heap: Extract-max places largest at end → ascending order.
4. Min-heap: Lowest priority number = most urgent → min-heap gives it first.
Use a min-heap of size k to efficiently merge — O(n log k)
Like a tournament bracket for k runners. Pick the fastest (min), record their time, and their next teammate enters. The heap keeps the bracket organized.
Everything you need to know about heaps in one slide
A heap is a partially ordered, complete binary tree stored in an array. It trades full sorting for fast access to the extreme element.
3 questions — pick the best answer
Q1: What is the time complexity of building a heap using bottom-up heapify?
Q2: In a max-heap with array [9, 7, 8, 3, 5], what is the left child of index 1?
Q3: To find the top-5 largest from a billion numbers, which heap do you use?
Given a min-heap, trace the downheap after removeMin
Min-heap array: [2, 5, 3, 8, 7, 6, 4]
After removeMin():
What is the final array after downheap?
What does this Java code print?
Enter your predictions: