◀ THE GRIND — HEAP / PRIORITY QUEUE

Kth Largest Element In a Stream

The drill: A running stream of numbers where each new value must instantly reveal the kth largest seen so far — the structure has to answer that question the moment a number lands, not by re-sorting everything.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

Numbers arrive one at a time into a live stream, and after every new number lands, the structure needs to instantly report the kth largest value seen across the whole stream so far.

The stream can start already holding some numbers before the first live add happens, and k stays fixed for the life of the structure — only the pool of numbers keeps growing from there.

Each add operation both records the new number and returns the current kth largest in one step, so the answer must be ready immediately, not computed by rescanning history.

EX 01
KthLargest(3, [4, 5, 8, 2])
add(3) → 4
add(5) → 5
add(10) → 5
add(9) → 8
add(4) → 8
K=3 WITH A FOUR-ELEMENT SEED
EX 02
KthLargest(1, [])
add(-3) → -3
add(-2) → -2
add(-4) → -2
K=1 IS JUST RUNNING MAX, EMPTY SEED, NEGATIVES
EX 03
KthLargest(2, [0])
add(5) → 0
add(-1) → 0
add(7) → 5
SEED SMALLER THAN K
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Re-sorting after every new number answers the question correctly but pays for the whole stream again and again. What's the smallest slice of the stream you actually need to remember to answer 'kth largest' instantly?

HINT 2 THE STRUCTURE

You never need the whole history — only the k largest values seen so far actually matter, and among those k, the smallest one IS the answer.

HINT 3 ONE STEP FROM THE ANSWER

Keep a min-heap capped at size k: push the new value, and if the heap grows past k, pop its smallest. The heap's top is always the kth largest.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE CAPPED HEAPPATTERN · MIN-HEAP OF SIZE Kk = 3 · seed = [4, 5, 8, 2] · add 3, 5, 10, 9, 4
new k=3
add 3
add 5
add 10
add 9
add 4
THE HEAP (SIZE ≤ K)
heap{4, 5, 8}
STEP 1

Seed [4, 5, 8, 2] with k=3 — heapify, then pop down to the 3 largest: 4, 5, 8.

STEP 1 / 7 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/kth-largest-element-in-a-stream.pyRACE PACE
LANG ▸
PACE ▸
class KthLargest:
    def __init__(self, k: int, nums: List[int]):
        self.k = k
        self.heap = list(nums)
        heapq.heapify(self.heap)
        while len(self.heap) > k:
            heapq.heappop(self.heap)

    def add(self, val: int) -> int:
        heapq.heappush(self.heap, val)
        if len(self.heap) > self.k:
            heapq.heappop(self.heap)
        return self.heap[0]
TIME O(LOG K) PER ADDSPACE O(K)PYTHON · RACE PACE · 13 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED