Kth Largest Element in a Stream
Report the k-th largest value after each new number by keeping only the top k values in a min-heap.
The problem
Design a class KthLargest that is created with an integer k and an initial array nums. Each call to add(val) puts val into the stream and returns the k-th largest value among everything added so far, where repeated values count separately. You can assume there are at least k values whenever add returns.
Input KthLargest(3, [6, 2, 9]), add(4), add(10), add(1), add(7)
Output [null, 4, 6, 6, 7]
After 10 arrives the three largest are 10, 9 and 6, so the answer is 6; the 1 is too small to change anything, and the 7 pushes the 6 out.
Input KthLargest(2, [3]), add(5), add(5), add(2)
Output [null, 3, 5, 5]
The stream starts with only one value, and duplicates count: after two 5s, the 2nd largest is 5.
Key constraint: There can be up to 10,000 calls to add, so sorting all the values again on every call is too slow.
How to spot the pattern
- Values keep arriving and you always need the k-th largest so far.
- Only the top k values ever matter; anything smaller can be thrown away for good.
The idea
The k-th largest value is the smallest of the k largest values. So keep exactly the k largest values seen so far in a min-heap, and its top is the answer. When a new value arrives, push it, and if the heap now holds more than k values, pop the smallest: a value that has fallen out of the top k can never become the answer again, because values are only ever added.
Brute force: Keep all the values in a list and sort it on every add, which costs O(n log n) per call.
Step by step
- 1In the constructor, store
kand add every value ofnumsthe same wayadddoes. - 2In
add(val), pushvalonto the min-heap. - 3If the heap now holds more than
kvalues, pop the smallest. - 4Return the top of the heap, which is the k-th largest value.
See the pattern move
The heaps and top k pattern on a small example. Step through it, or press play.
Code
import heapq
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.heap = [] # min-heap holding the k largest values seen so far
for num in nums:
self.add(num)
def add(self, val: int) -> int:
heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap) # it can never be the answer again
return self.heap[0]Complexity
Time
O(log k)
Space
O(k)
Each add does one push and at most one pop on a heap of at most k + 1 values; the constructor does this once for each of the n starting values, O(n log k) in total.
Watch out for
- Keeping every value in a max-heap: finding the k-th largest then means popping k values on every call.
- Popping the smallest before pushing the new value: if the new value is even smaller, the heap ends up without the real k-th largest.
- Assuming the heap is full from the start:
numscan hold fewer thankvalues, so only pop when the size goes abovek.
Follow-up questions
Why a min-heap and not a max-heap?
The answer is the smallest of the top k, so you need quick access to that smallest value and quick removal of anything that drops below it. A min-heap of size k gives both in O(log k).
What if values can also be removed from the stream?
A heap can't delete an arbitrary value quickly. Use a balanced tree or sorted multiset that can find the k-th largest in O(log n), or two heaps with lazy deletion.
In Hinglish
Sirf top k values ek min-heap mein rakho. Heap ka sabse chhota element hi k-th largest hai, aur jo top k se bahar gir gaya woh kabhi wapas kaam nahi aayega.