703. Kth Largest Element in a Stream
Practice Kth Largest Element in a Stream for free on NudgeCode: Easy, Heap pattern. Write it in Python or JavaScript, run the tests in your browser, and ask for a hint when you are stuck.
Design a class that tracks the k-th largest value in a growing stream of numbers (counting duplicates, so it is the k-th value in sorted descending order).
- The constructor receives
kand the initial numbersnums. add(val)appendsvalto the stream and returns the currentk-th largest value.
Each test is a list of operations and their arguments; the expected output lists what each call returns (null for the constructor and for calls that return nothing).
Example
["KthLargest","add","add","add","add","add"]
[[3,[4,5,8,2]],[3],[5],[10],[9],[4]]
-> [null,4,5,5,8,8]
Constraints
- 1 <= k <= 10^4
- 0 <= nums.length <= 10^4
- -10^4 <= nums[i], val <= 10^4
- There are at least
knumbers in the stream wheneveraddreturns