Min and max heaps for priority-based access, used in scheduling, graph algorithms, and top-K problems.
3 algorithms7 problems
3 algorithms. Each one builds on the last.
A min heap of end times counts the rooms a day of meetings needs.
O(N log N) time · O(N) spaceVisualizeA heap answers one question fast, over and over: what is the smallest (or largest) value right now, while values keep arriving and leaving. That makes it the engine behind priority queues, Dijkstra, event timers, merging k sorted lists, top k problems and heap sort. The four pages here go from the two kinds of heap, to building one from a ready array, to a classic interview problem that runs on one.
A heap is a complete binary tree packed into an array, with children of index i at 2i + 1 and 2i + 2. The only promise is between a parent and its children, so the root is the extreme value but the rest is only partly ordered. Each insert or extract is repaired by swapping along a single path from the root to a leaf or back up, and that path is about log₂ N long.
Choose min or max by which end you keep pulling from. Use build when every value is known up front and insert when they trickle in. The common mistake is treating the heap array as sorted: only index 0 is guaranteed, and reading left to right gives a jumble. If you need everything in order, you still extract values one at a time.