Top-K Everything: Heap Questions That Actually Show Up in Java Interviews
“Find the k largest elements in this array.” Most candidates reach for Arrays.sort() and stop. It works. It’s O(n log n). A stronger answer reaches for the heap: sorting processes all n elements in O(n log n) time, while a bounded heap takes O(n log k) and maintains only k candidates — preferable when k is small relative to n, or when the input arrives as a stream. For 1 ≤ k ≤ n, the heap uses O(k) auxiliary space, and the returned result uses O(k) output space. This post builds four common heap patterns that cover a wide range of top-k questions asked in Java interviews, with working code, the complexity math, and the PriorityQueue traps that quietly sink candidates. ...