We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
An easy heap / priority queue problem, graded against 6 test cases (3 of them hidden).
A priority queue for "top k" and streaming-median questions.
Reach for it when you see: "Top/smallest k", a running median, or repeatedly needing the current minimum.
More Heap / Priority Queueproblems →The instinct for "kth largest" is a max-heap, and that is the wrong structure. You do not need every value ordered - only the boundary between the top k and everything else. A min-heap capped at size k holds exactly the k largest values seen, and its root is the smallest of those: the kth largest overall.
Each add is a push followed by a pop when the size exceeds k, both O(log k), and the answer is always available at the root in O(1). Values that fall out of the top k are discarded permanently, which is what keeps memory at O(k) rather than O(n) - the property that matters for an unbounded stream.
Compare the alternatives: re-sorting is O(n log n) per add, and a max-heap of everything answers a query in O(k log n) since you must pop k times and push them back. The size-k min-heap beats both, and generalizes directly to "top k frequent" and "k closest points".
Note the values are not deduplicated - the kth largest in sorted order counts repeats, which is why a stream of identical values returns that value.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.