EasyTreeDesignBinary Search TreeHeap (Priority Queue)Data StreamBinary Tree

Kth Largest Element in a Stream

LeetCode
1 approach, code in all languages

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.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now