mediumHeapHeap / Priority Queue

Kth Largest Element in an Array

mediumTime: O(n log k)Space: O(k)

Signals to notice

find kth largest elementpartial sortdon't need full ordering

Brute force first

Sort the entire array and return nums[n-k]. Full sort when you only need one element. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Min-heap of size k: the heap's minimum is always the kth largest. Process all elements — if larger than heap min, replace. Or use Quickselect for average. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

A min-heap of size k contains the k largest elements. The smallest of those (the heap top) is by definition the kth largest overall. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

Using a max-heap of all n elements — that's which is worse than the min-heap approach for large n and small k. The fix is usually to return to the meaning of each move, not just the steps themselves.

Heap / Priority Queue Pattern