Pattern visualizer
Kth Largest Element in a Stream
The stream can grow forever, but only rank k ever matters — anything smaller than the kth largest can never become it and never displace it either. So keep just the k largest values seen so far in a min-heap: its root, the smallest of that top-k group, is by definition the kth largest overall. Every add is push, evict the new smallest if the heap overflows past k, then read the root. Animated on: Design a class that finds the kth largest element in a growing stream. Constructed with k=3 and nums=[4,5,8,2], then add(3), add(5), add(10), add(9), add(4) must return [4, 5, 5, 8, 8]..
A size-k min-heap: the root is always the answer
Constructor pushes 4 from the initial array. Heap now holds [4] — still under capacity k=3, so nothing is evicted yet.
1FUNCTION KthLargest(k, nums):2 heap <- EMPTY MIN-HEAP3 FOR num IN nums:4 PUSH num INTO heap5 IF SIZE(heap) > k:6 POP-MIN(heap)7FUNCTION add(val):8 PUSH val INTO heap9 IF SIZE(heap) > k:10 POP-MIN(heap)11 RETURN heap[0]
← / → step · space play · Home restart