Problem Description
We need to implement a class KthLargest that maintains a stream of test scores and returns the kth largest score after each new submission. The kth largest element is defined as the kth highest score in the sorted order of all scores seen so far.
Key Insights
- Use a min-heap (priority queue) of fixed size k.
- The heap always contains the k largest elements; the smallest element in the heap is the kth largest overall.
- When a new test score is added:
- If the heap has less than k elements, simply add the score.
- If the heap is full and the new score is greater than the smallest (heap root), replace the root.
- Each add operation runs in O(log k) time.
Space and Time Complexity
Time Complexity: O(log k) per add operation, O(n log k) to build the initial heap. Space Complexity: O(k) for maintaining the heap.
Solution
We use a min-heap to track the k largest numbers. When initializing, we add numbers from the given list to the heap, ensuring not to exceed a size of k. For each add operation, if the new number is greater than the heap minimum, we replace the minimum. The kth largest number is always accessible as the minimum element in the heap.