Kth Largest Element in an Array
Return the k-th largest element (not distinct) without fully sorting.
Open on LeetCode ↗Intuition
Keep a min-heap of the k largest seen so far — its root is always the current k-th largest. Anything smaller than the root can't matter; anything bigger evicts the root. n pushes into a size-k heap beats a full sort when k ≪ n.
Approach
Why a MIN-heap for largest
The gatekeeper of 'top k' is the smallest member of that club — exactly what a min-heap exposes at its root.
Stream the array through
Seed the heap with the first k values, then for each remaining value compare it against the root. If it is not larger, it cannot belong to the top k — skip it entirely. If it is larger, heapreplace swaps it in and sifts down in one step, evicting the old minimum. Invariant: the heap always holds the k largest elements seen so far.
Alternative: quickselect
Partition around a pivot and recurse into the side containing index n−k — O(n) average, O(n²) worst; the heap is the safe default.
Solution & live demo
Edge cases
Heap holds everything; root is the minimum — correct.
'k-th largest' counts repeats; the heap does so naturally.