EasyTreeDesignBinary Search TreeHeap (Priority Queue)Data StreamBinary Tree

Kth Largest Element in a Stream

1 approach, code in every language

Problem description

Design a class that tracks the `k`-th largest element within a stream of integers. Note this is the `k`-th largest in sorted order, not the `k`-th distinct value.

Implement the class:

- `KthLargest(k, nums)` initializes the object with the integer `k` and an initial list of integers `nums`. - `add(val)` appends `val` to the stream and returns the element that is currently the `k`-th largest.

It is guaranteed that there will be at least `k` elements in the stream when `add` is called.

Example 1

Input: ["KthLargest","add","add","add","add","add"] [[3,[4,5,8,2]],[3],[5],[10],[9],[4]]

Output: [null, 4, 5, 5, 8, 8]

Seeded with k = 3 and [4,5,8,2] the 3rd largest is 4. add(3) -> 4, add(5) -> 5, add(10) -> 5, add(9) -> 8, add(4) -> 8.

Example 2

Input: ["KthLargest","add","add"] [[1,[]],[-1],[5]]

Output: [null, -1, 5]

With k = 1 the answer is simply the maximum seen so far. After adding -1 the largest is -1; after adding 5 the largest is 5.

Constraints

  • 1 <= k <= 10^4
  • 0 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • -10^4 <= val <= 10^4
  • At most 10^4 calls are made to add.

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free