A heap gives you the smallest element of a collection in O(1) and lets you insert or remove in O(log n). Python's heapq module turns any list into a min-heap.
At a ski-jump qualifier, scores come in one jump at a time and the best k jumps so far go through to the final. The scoreboard shows the current cut-off: the k-th highest score posted so far. Write a class KthLargest that keeps that cut-off up to date:
KthLargest(k, nums)sets up the board with the integerkand the scores already posted,nums(possibly empty).add(val)posts the scorevaland returns the new cut-off, thek-th largest score so far.
Every add has an answer: once val is posted there are at least k scores (nums alone may hold fewer than k). Equal scores count separately: the 2nd largest of [5, 5, 1] is 5.
Examples
Input:
KthLargest(3, [7, 2, 9, 4])
add(5) -> 5 scores so far: 2 4 5 7 9, 3rd largest is 5
add(1) -> 5 a low score leaves the cut-off alone
add(10) -> 7 top three: 10 9 7
add(8) -> 8
add(6) -> 8
Output: [None, 5, 5, 7, 8, 8]
Constraints
1 <= k <= 10000 <= len(nums) <= 1000, and at most 1000 calls toadd- Re-sorting the whole stream on every
addworks, but a heap of sizekis the intended O(log k) solution.
Goals
- Use heapq.heappush and heapq.heappop on a plain Python list
- Keep a min-heap of bounded size k so its smallest element is the k-th largest overall
- Maintain state across method calls in a class