Given an array and k, return the kth largest element in sorted order (not the kth distinct one). Try to avoid sorting the whole array.
Before you code
Sorting is O(n log n). Two faster approaches: a min-heap of the k largest seen so far (O(n log k)), or quickselect, which partitions like quick sort but only recurses into one side (O(n) expected).
Hints
- Heap: push each value; when the heap exceeds k, pop the smallest. The root is the answer.
- Quickselect: the kth largest is at index n − k in sorted order. Partition, then continue only in the side that contains that index.
- Use a random pivot for quickselect, or adversarial inputs make it quadratic.
Production & complexity notes
When solving Kth largest element in an array on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Top-k and merging streams to reinforce the underlying pattern.
What it practices
The top-k heap and its alternatives, from Top-k and merging streams.