Loading...
Loading...
Tier II · Intermediate
Always knowing the smallest (or largest) element while the data keeps changing.
A heap keeps the smallest (or largest) element of a changing collection one read away. It is an array read as a complete binary tree where every parent beats its children and nothing else is ordered, so a push or a pop only touches one root-to-leaf path.
| C++ | Python | Java | |
|---|---|---|---|
| Type | priority_queue | heapq | PriorityQueue |
| Default order | largest first | smallest first | smallest first |
A heap only shows you its top element. It cannot look up or delete an arbitrary value in the middle, so removing specific elements requires lazy deletion, where you record the value as deleted in a map or set and discard it once it rises to the top. To track the largest values in a stream, keep a min-heap of size and evict its top whenever a bigger value arrives, since the smallest survivor is the threshold to beat.
| Operation | Heap | Sorted array |
|---|---|---|
| Peek at the extreme | ||
| Insert or pop the extreme | ||
| Build from values |
Reach for one when a problem wants the current extreme again and again while the collection keeps changing, such as tracking the top of a stream, merging sorted lists one cursor at a time, or revising the worst earlier choice in a greedy pass.
The problems below start with repeated extremes and a size- heap, move through -way merge cursors and greedy passes that trade or combine the smallest choices, and end with two heaps maintaining a sliding median under lazy deletion.
Recommended first: Hash Maps.
You've cleared 0 of 9 problems in these. You can dive in anyway.