Search⌘ K
AI Features

Problem: Kth Largest Element in a Stream

Explore how to dynamically track the kth largest element from a continuous stream of values using a min heap data structure. Understand how to efficiently insert new scores and maintain only the top k values for real-time retrieval. This lesson helps you implement the KthLargest class in JavaScript to solve practical problems involving streaming data and priority management.

Statement

You are part of a university admissions office that needs to dynamically track the kth highest test score among applicants in real time. This functionality is critical for determining cutoff marks for interviews and admissions as new applicants continue to submit their scores.

You need to implement a class that, given an integer, k, manages a continuous stream of test scores. Each time a new score is added, the class should return the kth highest score among all scores received so far, i.e., the score that would appear in the kthk^{th} position if the scores were sorted in descending order.

Implement the KthLargest class:

  • Constructor: Initializes the object with the integer k and the initial stream of test scores nums.

  • int add(int val): This function adds a new test score val to the stream and returns the kth highest score among all scores seen so far.

Constraints:

  • 1k1031 \leq k \leq 10^3
  • 00 \leq nums.length
...