 All Problems
Kth Largest Element in a Stream
easy
heap
design
arrays
amazon
google

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in sorted order, not the kth distinct element.

You are given an initial array and will repeatedly receive new integers. After each new addition, output the kth largest element.

Example:

Input:
2
4 5 8 2
3
5
10
9

Output:
4
5
8
8

Explanation: k=2, initial=[4,5,8,2]. After adding 3 → sorted [2,3,4,5,8], 2nd largest=4. After 5 → 5. After 10 → 8. After 9 → 8.

Constraints:

  • 1 ≤ k ≤ 10⁴
  • 0 ≤ initial array length ≤ 10⁴
  • -10⁴ ≤ nums[i], val ≤ 10⁴
  • At most 10⁴ calls to add.
  • It is guaranteed that there will always be at least k elements in the array when you search for the kth element.

Input format: First line: k. Second line: space-separated initial array (may be empty, represented by a blank line). Then each subsequent line is a new number to add; print the kth largest after each.

Output format: One integer per add operation.

Run to check your code against the sample cases, or submit to run every case