Implement a class KthLargest to find the kth largest number in a stream. It should have the following methods:
Note that it is the kth largest element in the sorted order, not the kth distinct element.
Input: [KthLargest(3, [1, 2, 3, 4]), add(5), add(2), add(7)]
Output: [null, 3, 3, 4]
Explanation: initial stream = [1, 2, 3, 4], k = 3.
add(5): stream = [1, 2, 3, 4, 5] -> returns 3
add(2): stream = [1, 2, 2, 3, 4, 5] -> returns 3
add(7): stream = [1, 2, 2, 3, 4, 5, 7] -> returns 4
Input: [KthLargest(2, [5, 5, 5, 5], add(2), add(6), add(60)]
Output: [null, 5, 5, 6]
Explanation: initial stream = [5, 5, 5, 5], k = 2.
add(2): stream = [5, 5, 5, 5, 2] -> returns 5
add(6): stream = [5, 5, 5, 5, 2, 6] -> returns 5
add(60): stream = [5, 5, 5, 5, 2, 6, 60] -> returns 6
Input: [KthLargest(4, [5, 1, 2, 7], add(8), add(2), add(6)]
Striver and the team have worked tirelessly over the past few days to bring this to you. Please bear with us a little more as we finalize everything.
Q: Why use a min-heap instead of a max-heap?
A: A min-heap of size k efficiently tracks the k-th largest element. The root always holds the k-th largest value, avoiding full sorting.
Q: Can we use sorting instead of a heap?
A: Sorting each time costs O(n log n), while heap operations are O(log k). Sorting is too slow for large data streams.
Q: How does this work in real-world applications?
A: Stock market analysis (track top k highest prices). Leaderboard ranking (finding k-th highest score). Data stream processing (analyzing incoming data efficiently).
Q: How would you find the k-th smallest element instead?
A: Use a max-heap of size k (instead of a min-heap). The largest value in the max-heap is the k-th smallest.