10
Two Heaps
Running median and scheduling.
4 pages
- Pattern 10: Two HeapsPattern guide
A max-heap of the smaller half and a min-heap of the larger half, kept balanced. The two heap tops straddle the median, so the median is O(1).
- LC 703Kth Largest Element in a Stream (LC 703)Easy
Keep a min-heap of exactly k largest values seen so far; the heap’s minimum is the kth largest.
- LC 1046Last Stone Weight (LC 1046)Easy
Repeatedly take the two heaviest stones using a max-heap; smash and push back the remainder until at most one stone remains.
- LC 215Kth Largest Element in an Array (LC 215)Medium
Either maintain a size-k min-heap of the largest values, or partition (QuickSelect) to place the kth largest without full sort.