A shortlist of the 3 tallest people seen so far: when someone taller arrives, the shortest person on the list is dropped.
Clues that point here
→ "K largest", "K smallest", "K most frequent", "K closest"
→ Kth largest element
→ Stream of data with a top-K query
Not this pattern when
✕ k is about n (just sort)
✕ Only the single max (one variable)
The template
A skeleton to adapt. The parts in comments are what changes from problem to problem.
Top K with a Heap · template
PriorityQueue<Integer> heap = new PriorityQueue<>(); // min-heap
for (int x : nums) {
heap.offer(x);
if (heap.size() > k) heap.poll(); // drop the smallest
}
return heap.peek(); // kth largest