Heaps and Priority Queues
Store a binary heap in an array, insert and remove in O(log n) with sift-up and sift-down, and use priority queues for scheduling and top-k problems.
Welcome back!
Step 1 of 10Learn
Always serve the most urgent first
An emergency room doesn't treat patients in arrival order; it treats the most urgent first. An operating system runs the highest-priority task next. A navigation app repeatedly explores the closest unexplored location. Each needs a priority queue: a collection where you can add items and always remove the one with the highest priority, often meaning the smallest key.
A sorted array could do this, but inserting costs O(n). An unsorted array makes insertion O(1) but finding the minimum O(n). The binary heap gets both down to O(log n).
A min-heap is a binary tree with two properties:
- Shape: it's a complete binary tree, with every level full except possibly the last, which fills from left to right.
- Heap order: every parent's key is less than or equal to its children's keys. So the smallest key is always at the root.
A max-heap flips the order so the largest is at the root. Note that a heap is only partially ordered: siblings can be in any order, and the array isn't sorted.
Because the tree is complete, it can be stored in a plain array with no pointers at all. Put the root at index 0 and fill level by level. Then for the node at index i:
- left child at 2i + 1
- right child at 2i + 2
- parent at floor((i − 1) / 2)
The array [2, 5, 3, 9, 6, 8] is a min-heap: 2 is the parent of 5 and 3, 5 is the parent of 9 and 6, and 3 is the parent of 8.
Step 2 of 10Practice · Work it out
In an array-based binary heap with the root at index 0, what is the index of the parent of the node at index 9?
Step 3 of 10Learn
Sift up, sift down
Heap operations keep both properties intact with a simple repair step.
Insert: add the new key at the end of the array, which keeps the tree complete. It may be smaller than its parent, breaking heap order, so sift up: while the key is smaller than its parent, swap them. The key rises until its parent is smaller or it reaches the root. A complete tree with n nodes has height about log₂ n, so this takes O(log n).
Extract-min: the minimum is at the root. Save it, move the last element of the array to the root, and shrink the array by one. Now sift down: while the moved key is larger than one of its children, swap it with the smaller child. Swapping with the smaller child is what guarantees the new parent is smaller than both children. Again O(log n).
Peek at the minimum is just reading index 0: O(1).
Build a heap from an unsorted array: you could insert n items one at a time for O(n log n), but there's a faster method. Sift down every non-leaf node, starting from the last one and moving backward to the root. Most nodes are near the bottom and barely move, and the total work works out to O(n).
What heaps don't do well: finding or deleting an arbitrary key requires searching the whole array, O(n), because the partial order doesn't tell you where it is.
Step 4 of 10Practice · Choose one
You insert 2 into the min-heap [3, 5, 8, 9, 6]. After sifting up, what is the array?
Step 5 of 10Practice · Code challenge
Write isMinHeap(arr) that returns true if the array satisfies the min-heap property (every parent is less than or equal to each of its children, using 0-based indices) and false otherwise.
isMinHeap([2, 5, 3, 9, 6, 8])isMinHeap([1, 2, 3, 4, 5])isMinHeap([5, 3, 8])isMinHeap([1, 4, 2, 3])isMinHeap([])isMinHeap([7, 7, 7])
Step 6 of 10Learn
Where heaps are used
Priority queues built on heaps show up in many important algorithms and systems:
- Scheduling: operating systems and job queues pick the highest-priority or earliest-deadline task next.
- Event simulation: process events in time order, always taking the next earliest event.
- Dijkstra's shortest-path algorithm and Prim's minimum spanning tree algorithm repeatedly take the closest unvisited vertex.
- Top-k problems: to find the 10 largest values in a stream of a billion, keep a min-heap of size 10. For each new value, if it's larger than the heap's minimum, replace the minimum. That's O(n log k) time and O(k) memory, far better than sorting everything.
- Merging k sorted lists: keep the front element of each list in a min-heap and repeatedly extract the smallest.
- Running median: maintain a max-heap for the lower half of values and a min-heap for the upper half.
Heapsort sorts an array by building a max-heap in O(n), then repeatedly swapping the root to the end and sifting down. It's O(n log n) in every case and in place, but not stable, and in practice it's often slower than quicksort because it jumps around memory.
Some languages provide heaps directly, such as Python's heapq module and Java's PriorityQueue. JavaScript has no built-in heap, so you implement one with an array and the index formulas, or use a library.
Step 7 of 10Practice · Sort into groups
Sort these binary heap operations by their time complexity.
Tap an item, then tap its group (or drag it there).
Step 8 of 10Note
Step 9 of 10Practice · True or false
The array representation of a valid min-heap is always sorted in ascending order.
Step 10 of 10Practice · What would you do?
What would you do?
A monitoring service receives a stream of about 50 million response times per day and must report the 100 slowest requests at any moment, using as little memory as possible. Which approach fits best?
Lesson complete!