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 withkand an initial list of scores (possibly empty).add(val)adds one score and returns thekth 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) → 8Constraints
1 <= k <= 10^40 <= nums.length <= 10^4-10^4 <= val <= 10^4- At most
10^4calls toadd. - Whenever
addreturns, the stream holds at leastkvalues.