Heap & Priority Queue
Always know the smallest (or largest) item — top-k, scheduling, merging, running medians.
This topic is part of Pro.
Free covers the C and Python courses, the first three DSA topics, the opening system design lessons and the beginner AI lessons, all with the full coach. Pro opens the rest of the library in the FollowtheDamnCode app.
What is in it
- 1How heaps workA complete binary tree stored in an array, kept in order by sifting up and sifting down. Pro
- 2Building a heap and heap sortHeapify n items in O(n), not O(n log n) — and sort in place by popping repeatedly. Pro
- 3Top-k problemsKeep a heap of only k items — a min-heap for the k largest — and pay O(n log k). Pro
- 4Heaps in simulations, merges, and mediansAlways act on the current smallest — combine sticks, merge k lists, and keep a running median with two heaps. Pro