Data Structures19 sections · 729 units
Open in Course

K-th Largest with Min-Heap

The counterintuitive choice

Why use a min-heap for k-th largest? It seems backwards. The trick: keep exactly kk elements in a min-heap.

The heap root is the smallest of these kk elements, which is the k-th largest overall. For each new element:

  • If smaller than heap root, ignore it (not in top kk)
  • If larger, remove the root and insert the new element

After processing all elements, the root is the k-th largest.