You are part of a university admissions office and need to keep track of the kth highest test score from applicants in real-time. This helps to determine cut-off marks for interviews and admissions dynamically as new applicants submit their scores.
You are tasked to implement a class which, for a given integer k, maintains a stream of test scores and continuously returns the kth highest test score after a new score has been submitted. More specifically, we are looking for the kth highest score in the sorted list of all scores.
Implement the KthLargest class:
KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of test scores nums.int add(int val) Adds a new test score val to the stream and returns the element representing the kth largest element in the pool of test scores so far. Input:
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output: [null, 4, 5, 5, 8, 8]
Explanation:
Input:
["KthLargest", "add", "add", "add", "add"]
[[4, [7, 7, 7, 7, 8, 3]], [2], [10], [9], [9]]
Output: [null, 7, 7, 7, 8]
Explanation:
For each addition of a new element into the stream, we can sort the elements and fetch the k-th largest element directly. This approach is straightforward but inefficient for larger inputs.
O(n log n) for sorting the list each time a new element is added (where n is the number of elements in the list).O(n) for storing the elements in a list.Maintain a sorted list at all times and ensure the list is sorted with each new insertion. This results in better time complexity than re-sorting the entire list.
O(k) for maintaining a sorted list by binary search and insertion.O(n) for storing the stream of numbers.Use a min-heap of size k to efficiently manage the k-th largest element. The min-heap will allow the smallest element to be on top, ensuring we can easily access the k-th largest element by maintaining heap size.
k.k, remove the smallest element (top of the heap).k.O(log k) for each addition (heap insertion and adjustment).O(k) for maintaining the heap of size k.