Heaps: paying only for the order you need
A heap is the structure you get by giving up almost all of sorting's guarantees and keeping one — the extreme element is at the front — and that single retained guarantee is enough for top-k, k-way merge, running medians, schedulers, and Dijkstra, at O(log n) per update instead of a re-sort.
What you'll be able to do
- Explain the array encoding of a binary heap and derive the parent and child index formulas
- Implement push and pop with sift-up and sift-down, and say which one each operation needs
- Prove that building a heap bottom-up is O(n) while n pushes are O(n log n), and measure the difference
- Solve top-k with a bounded heap of size k, and explain why finding the k largest uses a min-heap
- Maintain a running median with two heaps, and state the invariant that keeps them balanced
Before this: sorting-and-comparators, stacks-and-queues
The rest of this lesson is in the app
A heap is the structure you get by giving up almost all of sorting's guarantees and keeping one — the extreme element is at the front — and that single retained guarantee is enough for top-k, k-way merge, running medians, schedulers, and Dijkstra, at O(log n) per update instead of a re-sort. This walkthrough runs about 28 minutes, with runnable code you can edit and re-run as you read.
Continue in ChannelPulseThe first module of every track is free to read on the web — see what's open in Coding & data structures.