Kth Largest Element in a Stream
Kth Largest Element in a Stream is LeetCode 703 (Easy). Design a class KthLargest:
KthLargest(k, nums)starts with the scores innums.add(val)adds one score and returns the k-th largest score so far. Repeated scores count separately.
There are up to 10⁴ starting scores and 10⁴ calls to add, and at least k scores exist whenever add returns.
- 0 <= nums.length <= 10⁴
- 1 <= k <= nums.length + 1
- -10⁴ <= nums[i] <= 10⁴
- -10⁴ <= val <= 10⁴
- At most 10⁴ calls will be made to add.
Intuition
Only the k largest values seen so far can ever be the answer, now or later. A smaller value already has k bigger values ahead of it, and new arrivals can only add more. So keep just those k values, in a min-heap:
- The root is the answer: the smallest of the k largest values is the k-th largest overall, and a min-heap keeps its smallest value at the root.
- Adding is push, then trim: push the new value, then pop the root whenever the heap holds more than k values. The value popped is the one that just fell out of the top k, which may be the new value itself.
A running rank ("the k-th best score so far", "the 100th fastest lap today") over data that keeps arriving calls for a heap capped at k, kept between calls.
Approach
Before reading on, decide which values can never be the answer again once k bigger ones have arrived. Then pick a structure whose cheapest value to read is exactly the answer. Aim for O(log k) per add.
Build the heap in the constructor
Store k, start with an empty min-heap, and call add on each starting number, so one rule fills the heap. In C++ a priority_queue is a max-heap unless you pass greater<int>; Java's PriorityQueue is already a min-heap.
Push the new value
Push val onto the heap. It moves up to its place in O(log k) swaps, and for a moment the heap may hold k + 1 values.
Pop the root if the heap is too big
If the heap now holds more than k values, pop the root. The root is the smallest of k + 1 values, so it cannot be in the top k, and removing it leaves exactly the k largest values seen so far.
Return the root
Return the root. The problem promises at least k values whenever add returns, so the heap is full and its root is the k-th largest; no empty-heap check is needed.
Code in Python, C++ and Java
Common pitfalls
Forgetting to trim after a push
def add(self, val):
heapq.heappush(self.heap, val)
return self.heap[0]heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap)
return self.heap[0]Without the pop the heap keeps every value, and its root becomes the smallest value ever seen. For k = 3, nums = [4, 5, 8, 2], add(3) returns 2 instead of 4.
Rejecting small values before the heap is full
if val > self.heap[0]:
heapq.heapreplace(self.heap, val)heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap)The guard only makes sense once k values are stored. For k = 2, nums = [5], add(1) must return 1, but the guard throws 1 away and returns 5. With nums = [] it reads heap[0] of an empty heap and crashes.
Using a max-heap
heapq.heappush(self.heap, -val)
if len(self.heap) > self.k:
heapq.heappop(self.heap)heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap)Popping from a max-heap removes the largest value, so the heap keeps the k smallest instead. For k = 1, nums = [1], add(2) returns 1 instead of 2.
Complexity
add does one push and at most one pop on a heap of at most k + 1 values. The constructor calls add once per starting number, O(n log k) in total. Only k values are stored, however long the stream runs.Kth largest: one array vs a stream
The two problems share a name, but how often the question is asked changes the best tool.
| Problem | Input | Best tool |
|---|---|---|
| Kth largest element in an array | one fixed array, one question | quickselect, O(n) on average; a size-k heap also works |
| Kth largest element in a stream (this page) | values keep arriving, a question after each one | a size-k min-heap kept between calls, O(log k) per value |
Kth Largest Element in a Stream FAQ
Why not keep a sorted list and insert with binary search?
Finding the spot is O(log n), but inserting into the middle of an array shifts up to n values, so each add costs O(n). It passes at these sizes, yet the heap does each add in O(log k) and stores only k values.