The problem. Design a class KthLargest that finds the kth largest value in a stream of numbers. The constructor KthLargest(k, nums) receives k and the first values. Each call to add(val) adds a value to the stream and returns the kth largest value so far. (The kth largest means in sorted order — duplicates count — and there are always at least k values when you're asked.)
KthLargest(3, [4, 5, 8, 2])
add(3) -> 4 the values are 2 3 4 5 8: the 3rd largest is 4
add(5) -> 5 2 3 4 5 5 8
add(10) -> 5 2 3 4 5 5 8 10
add(9) -> 8 2 3 4 5 5 8 9 10
add(4) -> 8Members only · free account
The rest of this lesson, with 7 more sections, 1 drawing, a dry-run simulator and code in JavaScript, Python, Java and C++, opens with a free account.
Not ready yet? The Arrays course is free to read, no account needed.
In the rest of this lesson