Return the kth largest element of an array (e.g. k=2 on [3,2,1,5,6,4] -> 5).
A clean approach maintains a min-heap of size k: push elements and evict the smallest whenever the heap exceeds k, so the root ends as the kth largest — O(n log k). Sorting is O(n log n); Quickselect averages O(n). Discuss the trade-off.
public static int kthLargest(int[] a, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>(); // min-heap
for (int x : a) {
heap.offer(x);
if (heap.size() > k) heap.poll();
}
return heap.peek();
}function kthLargest(a, k) {
// simple: sort descending and index (O(n log n))
return [...a].sort((x, y) => y - x)[k - 1];
}import heapq
def kth_largest(a, k):
return heapq.nlargest(k, a)[-1]Top-k selection powers leaderboards, "slowest N requests", and streaming analytics where a full sort is wasteful.
The array has a billion elements but k is small. Why is a size-k heap better than sorting?