Kth Largest Element in a Stream

easyTests passed 2026-11-11v1.0.0

1. Core Invariant / The Trick

Maintain a **min-heap** capped at size `k`: elements smaller than the k-th largest are evicted on `heappop`. The root `heap[0]` is always the k-th largest element.

2. Complexity Bounds & Proof

Heapifying N initial items and trimming to k takes O(N log k); every subsequent `add(val)` takes O(log k).

3. Minimal Idiomatic Code

class KthLargest:
    def __init__(self, k: int, nums: list[int]):
        self.k = k
        self.h = list(nums)
        heapq.heapify(self.h)
        while len(self.h) > k:
            heapq.heappop(self.h)

    def add(self, val: int) -> int:
        if len(self.h) < self.k:
            heapq.heappush(self.h, val)
        elif val > self.h[0]:
            heapq.heapreplace(self.h, val)
        return self.h[0]

4. Failure Modes & Interview Follow-ups

Pitfalls:- Using a max-heap requires storing all N seen elements and scanning k pops per query. - Calling `add` when heap size is still `k - 1` must push first before reading `heap[0]`.
Follow-ups:- Offline static array: Quickselect finds the k-th largest in O(N) expected time without extra memory.

Personal Notes & Scratchpad (Local-First Yjs CRDT)

Saved instantaneously in IndexedDB. Streams live across peers via Hocuspocus when signed in.

Related Invariants

Browser Scratchpad
Console Output
Click Run or press Cmd/Ctrl+Enter to execute locally in a Web Worker.