PracticeNeetCode ↗LeetCode ↗
Design a class that keeps track of the kth largest element in a growing stream of numbers. It's initialized with an integer k and a starting list of numbers, and supports adding one new number at a time, returning the current kth largest value after each add.
k largest values seen so far.k elements, its smallest member can never be the answer, so pop it.kth largest, because it's the smallest of the top-k group.nums into a min-heap, then pop down until only k elements remain.add(val): push val onto the heap.k elements, pop the smallest.kth largest.Time: O(log k) per add — Space: O(k)
import heapq
class KthLargest:
def __init__(self, k: int, nums: list[int]):
self.k = k
self.heap = nums
heapq.heapify(self.heap)
while len(self.heap) > k:
heapq.heappop(self.heap)
def add(self, val: int) -> int:
heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap)
return self.heap[0]How the solution above works, piece by piece.
heap[0], is then exactly the k-th largest overall.__init__: heapify the starting numbers and pop until only k remain.add: push the new value; if the heap grows past k, pop the smallest (it can no longer be in the top k). Return heap[0].add is O(log k); memory is O(k) no matter how long the stream is.Running it on k = 3, nums = [4, 5, 8, 2], then add(3), add(5), add(10):