Data Structures19 sections · 729 units
Open in Course

Kth Largest - Algorithm

Bounded min-heap

Maintain a min-heap of size kk:

1.1. Insert the first kk elements into the heap.

2.2. For each remaining element:

  • If it's larger than the heap root, extract root and insert element.
  • Otherwise, skip it.

3.3. Return the heap root. The heap always contains the kk largest elements seen so far. Its root (minimum of these kk) is the k-th largest overall. Time: O(nlogk)O(n \log k). Space: O(k)O(k).