Imagine you're working for a university admissions office during application season. As test scores stream in real-time, you need to continuously track the k-th highest score to determine admission cutoffs dynamically.
Your task is to implement a KthLargest class that efficiently maintains this information:
- Constructor:
KthLargest(int k, int[] nums)- Initialize with the value k and an initial array of scores - Add Method:
int add(int val)- Add a new score and return the current k-th largest score
The key challenge is that you need to return the k-th largest element after each addition, not just once. This requires an efficient data structure that can handle frequent insertions while quickly retrieving the k-th largest element.
Example: If k=3 and you have scores [4, 5, 8, 2], the 3rd largest is 4. When you add 3, the new 3rd largest becomes 4. When you add 5, it becomes 5.
Input & Output
Visualization
Time & Space Complexity
Each add operation involves at most one heap operation (insert/replace) which takes O(log k)
Only store K elements in the min-heap
Constraints
- 1 โค k โค 104
- 0 โค nums.length โค 104
- -104 โค nums[i] โค 104
- -104 โค val โค 104
- At most 104 calls will be made to add
- It is guaranteed that there will be at least k elements in the array when you search for the kth element.