LeetCode 703 Kth Largest Element in a Stream - Solution

The core idea

Maintain a min-heap of size k containing the k largest elements seen so far.

The heap's minimum is always the kth largest element. When a new value arrives:

  • If heap size < k, just add it.
  • If new value > heap minimum, remove the minimum and add the new value.
  • Otherwise, the new value isn't among the top k, ignore it.

After each add, return the heap minimum.

Why min-heap? Because we want quick access to the smallest of the k largest. That's the boundary element we might need to evict.