13
Top 'K' Elements
PriorityQueue and heap selection.
4 pages
- Pattern 13: Top 'K' ElementsPattern guide
The counter-intuitive rule: for the k LARGEST, use a MIN-heap of size k. The top is the weakest survivor, so it is exactly the one to evict when something…
- LC 703Kth Largest Element in a Stream (LC 703)Easy
Keep a min-heap of size k so the smallest value in the heap is always the k-th largest in the entire stream seen so far.
- LC 973K Closest Points to Origin (LC 973)Medium
Track the k smallest distances using a max-heap of size k keyed by distance (evict the farthest when you have k + 1 candidates).
- LC 692Top K Frequent Words (LC 692)Medium
Count frequencies with a map, then use a size-k min-heap with a custom order so the root is always the worst kept candidate (lowest freq, then…