Kth Largest Element in a Stream

Easy#703k largest

Build a class that gets a number k and a starting list of numbers, and then gets more numbers one at a time. After each new number it returns the k-th largest of all the numbers it has seen, repeats counted. Our example: k = 3, the list [6, 2, 9, 4, 1], then add(5), add(3), add(10) — they return 5, 5 and 6.

input
Calls one after another: KthLargest(k, nums) gets k and the numbers to start with, then each add(val) gets one more number.
returns
add(val) returns the k-th largest of all the numbers so far, val included and repeats counted.
constraints
  • 1 ≤ calls of add ≤ 2000
  • 0 ≤ nums.length ≤ 2000
  • 1 ≤ k ≤ nums.length + 1
  • −10⁴ ≤ nums[i], val ≤ 10⁴
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} k
 * @param {number[]} nums
 */
var KthLargest = function(k, nums) {

};

/**
 * @param {number} val
 * @return {number}
 */
KthLargest.prototype.add = function(val) {

};

/**
 * Your KthLargest object will be instantiated and called as such:
 * var obj = new KthLargest(k, nums)
 * var param_1 = obj.add(val)
 */
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more heap and top k problems

Pattern “Heap and top K” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.