Kth largest element
Keep a min-heap of size k. Each value either beats the smallest kept one and replaces it, or is discarded immediately. The heap's root is the answer. O(n log k) time and O(k) memory — which matters when n is enormous and k is ten.
Overview
Three answers, and the reason to choose
Sort and index. sorted(a)[-k]. O(n log n), one line, and the right answer in real code for any array that fits in memory.
Min-heap of size k. O(n log k) time and O(k) memory. The only one that works on a stream, or when n is far larger than memory.
Quickselect. O(n) average by partitioning and recursing into one side only. O(n²) worst case with a bad pivot, fixable with a random one.
Interviewers are usually listening for whether you notice the heap is bounded by k rather than n.
Step through it
What to watch
- The heap never grows beyond k — that is the memory bound.
- A value smaller than the root is discarded without being stored.
- The root is always the smallest of the k largest.
Say this out loud
"Min-heap of size k: O(n log k) time, O(k) space. Sorting is O(n log n) and quickselect is O(n) average but O(n²) worst case. For a stream, or when n doesn't fit in memory, the heap is the only one that works."