The size-K heap trick
All three problems share one move: maintain a heap holding only the K best candidates seen so far. The trick is the direction: to keep the K largest values, use a min-heap so the smallest of your keepers sits at the root, ready to be kicked out the moment something bigger arrives.
Push each element; if the heap exceeds K, pop the root. After one pass the heap holds exactly the K you want, and its root is the Kth element. K Closest Points is the same idea with distance as the key (max-heap of size K by distance).
for x in nums:
heap.push(x)
if heap.size() > K:
heap.pop() # drop smallest
return heap.top() # Kth largest
N pushes/pops on a heap capped at size K. Far better than sorting's O(N log N) when K is small.
The heap never grows past K elements.
Step-by-step trace
| # | Action | Element | Heap (root first) | Size | Root |
|---|