Priority Queue

Kth Largest Element in a Stream

Easy
Solve it on LeetCode ↗

The problem

Design a class whose add(val) inserts a value and returns the kth largest element seen so far.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Maintain a min-heap holding at most k elements.
  2. 2add: push the value; if the heap exceeds k, pop the minimum.
  3. 3The root is the answer after every add.

Key insight

A min-heap tracking the k LARGEST feels backwards but is exactly right: the smallest of the top-k guards the door, and anything that beats it evicts it.

The solution

Watch out for

  • The initial array may hold fewer than k elements — the heap fills up through later adds.
  • JS heap-popping: replace the root with the last element THEN sift down; naive pop reorders wrong.