Courses / DSA Patterns for Working Engineers / Chapter 7
Module 3 · Heaps, k-way merges and top k · Chapter 7 of 39
Heaps and Two Heaps: Running Medians and Priority Scheduling
Builds on Intervals: Merging, Inserting and Counting Overlaps. Next up: K-Way Merge: Combining Sorted Streams With a Heap.
Part 1 · Introduction to heaps
What a heap is
Task schedulers, order books and delivery dispatchers all need the same thing: keep a changing collection of items and always be able to take out the most urgent one quickly. A heap is the standard structure for that job.
A priority queue is an abstract container with two operations: add an item, and remove the item with the highest priority. A binary heap is the usual way to build one. It keeps the items in an array arranged so that every item is ordered with respect to its two children. In a min-heap, every item is less than or equal to both of its children, so the smallest item is always at index 0. In a max-heap it is the other way round and the largest item sits at index 0.
The array hides a tree. Picture a binary tree filled level by level, left to right, with no gaps. The item at index i has its children at indexes 2i + 1 and 2i + 2, and its parent at (i - 1) >> 1. No pointers are needed, and the tree has about log2 n levels for n items, which is why the heap operations are fast.
| Operation | What it does | Cost |
|---|---|---|
| peek |