TRT
Sign in
easyCoreLeetCode#size-k min-heap

Kth largest element in a stream

Report the kth largest value after each insertion into a stream, with a min-heap that never holds more than k values.

The Runtime Theory Team1 min read
Taught inThe heap property in an arrayPro — members onlyA priority queue always hands out its smallest (or largest) item next. A binary heap implements it as a complete tree stored in a plain array, where parents and children are found by arithmetic instead of pointers.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ink = 3, nums = [4, 5, 8, 2]; add(3), add(5), add(10), add(9), add(4)

out4, 5, 5, 8, 8

ink = 1, nums = []; add(-3), add(-2)

out-3, -2

Design a class that is constructed with k and an initial list of numbers, and whose add(val) inserts a value and returns the kth largest value seen so far.

Before you code

Keeping every value sorted makes each add O(n). You only ever need the kth largest, which is the smallest of the top k: the root of a min-heap that holds exactly the top k.

Hints

  1. Keep a min-heap of at most k values.
  2. On add, push the value; if the heap now has more than k values, pop the smallest.
  3. The answer is the heap's root, heap[0].

Production & complexity notes

When solving Kth largest element in a stream on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in The heap property in an array to reinforce the underlying pattern.

What it practices

A min-heap's root as a running threshold, from The heap property in an array.

Not started

Sign in to save your learning progress.

Sign in to save