mediumHeapHeap / Priority Queue

Kth Largest Element in an Array

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

Recognize the pattern

find kth largest elementpartial sortdon't need full ordering

Brute force idea

If you approach Kth Largest Element in an Array in the most literal way possible, you get this: 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.

Better approach

The deeper shift in Kth Largest Element in an Array is this: 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.

Key invariant

At the center of Kth Largest Element in an Array is one steady idea: 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.

Watch out for

One easy way to drift off course in Kth Largest Element in an Array is this: 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