Skip to content

Kth Largest Element in a Stream

EasyHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.

Build a class KthLargest that watches a stream of test scores and always knows the kth largest score so far. Duplicates count separately.

  • KthLargest(k, nums) starts with k and an initial list of scores (possibly empty).
  • add(val) adds one score and returns the kth largest value in the stream after adding it.
kl = KthLargest(3, [4, 5, 8, 2])
kl.add(3)    →  4
kl.add(5)    →  5
kl.add(10)   →  5
kl.add(9)    →  8
kl.add(4)    →  8

Constraints

  • 1 <= k <= 10^4
  • 0 <= nums.length <= 10^4
  • -10^4 <= val <= 10^4
  • At most 10^4 calls to add.
  • Whenever add returns, the stream holds at least k values.