Kth Largest Element in a Stream
Design a class KthLargest that tracks the kth largest value in a stream of numbers (the kth largest overall, not the kth distinct). The constructor receives k and an initial array nums. Each call to add(val) inserts val into the stream and returns the kth largest element seen so far.
Open official problem prompt ↗Answer 'what is the kth largest value so far?' after every insertion into a live stream, without re-sorting each time.
Think of a leaderboard that only keeps the top k scores. When a new score arrives you add it, then bump off the current lowest of the top k. The lowest survivor is exactly the kth-best score.
- Input
- KthLargest(3, [4, 5, 8, 2]); then add(3), add(5), add(10), add(9), add(4)
- Output
- [4, 5, 5, 8, 8]
- Why
- After each add the 3rd-largest value is reported: with {2,4,5,8,3} it is 4, then {..5} makes it 5, then 10 pushes it to 5, then 9 to 8, then 4 to 8.
1 <= k <= 10^40 <= nums.length <= 10^4-10^4 <= nums[i] <= 10^4-10^4 <= val <= 10^4At most 10^4 calls to addIt is guaranteed there are at least k elements when add is called