LeetCode #703 Easy

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 in nums.
  • 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.

Constraints
  • 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.
heapdesignstream
Open on LeetCode ↗
02

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.
How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1import heapq
▶2 
▶3class KthLargest:
▶4 def __init__(self, k, nums):
▶5 self.k = k
▶6 self.heap = []
▶7 for x in nums:
▶8 self.add(x)
▶9 
▶10 def add(self, val):
▶11 heapq.heappush(self.heap, val)
▶12 if len(self.heap) > self.k:
▶13 heapq.heappop(self.heap)
▶14 return self.heap[0]
stream so far4min-heap, 1 of k 34rootadd returnsnothing yetstart value 4 → push it
start value4
heap size1k = 3
Push 4. It moves up past any larger parent, so the smallest value stays at the root. The heap holds only 1 of 3 values, so nothing is dropped.
stream so far45min-heap, 2 of k 345rootadd returnsnothing yetstart value 5 → push it
start value5
heap size2k = 3
Push 5. It moves up past any larger parent, so the smallest value stays at the root. The heap holds only 2 of 3 values, so nothing is dropped.
stream so far458min-heap, 3 of k 3458root: k-th largestadd returnsnothing yetstart value 8 → push it
start value8
heap size3k = 3
Push 8. It moves up past any larger parent, so the smallest value stays at the root. The heap holds exactly k values, nothing is dropped.
stream so far4582min-heap, 4 of k 32485rootadd returnsnothing yetstart value 2 → push it, heap now holds 4
start value2
heap size4k = 3
Push 2. It moves up past any larger parent, so the smallest value stays at the root. The heap now holds 4 values, one more than k, so one has to go.
stream so far4582min-heap, 3 of k 3458root: k-th largestadd returnsnothing yetpop the smallest, 2 → keep the top 3
dropped2
root4k-th largest
Pop the root, 2. It is the smallest of 4 values, so 3 values are bigger and it can never be the k-th largest again, which is why the value just added leaves at once. The new root, 4, is the k-th largest of the starting values.
stream so far45823min-heap, 4 of k 33485rootadd returnsnothing yetadd 3 → push it, heap now holds 4
add3
heap size4k = 3
Push 3. It moves up past any larger parent, so the smallest value stays at the root. The heap now holds 4 values, one more than k, so one has to go.
stream so far45823min-heap, 3 of k 3458root: k-th largestadd returns4pop the smallest, 3 → return 4
dropped3
root4k-th largest
Pop the root, 3. It is the smallest of 4 values, so 3 values are bigger and it can never be the k-th largest again, which is why the value just added leaves at once. The new root, 4, is the k-th largest so far, and add returns it.
stream so far458235min-heap, 4 of k 34585rootadd returns4add 5 → push it, heap now holds 4
add5
heap size4k = 3
Push 5. It moves up past any larger parent, so the smallest value stays at the root. The heap now holds 4 values, one more than k, so one has to go.
stream so far458235min-heap, 3 of k 3558root: k-th largestadd returns45pop the smallest, 4 → return 5
dropped4
root5k-th largest
Pop the root, 4. It is the smallest of 4 values, so 3 values are bigger and it can never be the k-th largest again. The new root, 5, is the k-th largest so far, and add returns it.
stream so far45823510min-heap, 4 of k 355810rootadd returns45add 10 → push it, heap now holds 4
add10
heap size4k = 3
Push 10. It moves up past any larger parent, so the smallest value stays at the root. The heap now holds 4 values, one more than k, so one has to go.
stream so far45823510min-heap, 3 of k 35108root: k-th largestadd returns455pop the smallest, 5 → return 5
dropped5
root5k-th largest
Pop the root, 5. It is the smallest of 4 values, so 3 values are bigger and it can never be the k-th largest again. The new root, 5, is the k-th largest so far, and add returns it.
stream so far458235109min-heap, 4 of k 359810rootadd returns455add 9 → push it, heap now holds 4
add9
heap size4k = 3
Push 9. It moves up past any larger parent, so the smallest value stays at the root. The heap now holds 4 values, one more than k, so one has to go.
stream so far458235109min-heap, 3 of k 38910root: k-th largestadd returns4558pop the smallest, 5 → return 8
dropped5
root8k-th largest
Pop the root, 5. It is the smallest of 4 values, so 3 values are bigger and it can never be the k-th largest again. The new root, 8, is the k-th largest so far, and add returns it.
stream so far4582351094min-heap, 4 of k 348109rootadd returns4558add 4 → push it, heap now holds 4
add4
heap size4k = 3
Push 4. It moves up past any larger parent, so the smallest value stays at the root. The heap now holds 4 values, one more than k, so one has to go.
stream so far4582351094min-heap, 3 of k 38910root: k-th largestadd returns45588pop the smallest, 4 → return 8
dropped4
root8k-th largest
Pop the root, 4. It is the smallest of 4 values, so 3 values are bigger and it can never be the k-th largest again, which is why the value just added leaves at once. The new root, 8, is the k-th largest so far, and add returns it.
05

Common pitfalls

Forgetting to trim after a push

✗ Wrong
def add(self, val):
    heapq.heappush(self.heap, val)
    return self.heap[0]
✓ Right
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

✗ Wrong
if val > self.heap[0]:
    heapq.heapreplace(self.heap, val)
✓ Right
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

✗ Wrong
heapq.heappush(self.heap, -val)
if len(self.heap) > self.k:
    heapq.heappop(self.heap)
✓ Right
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.

06

Complexity

Time
O(log k) per add
Space
O(k)
Each 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.
07

Kth largest: one array vs a stream

The two problems share a name, but how often the question is asked changes the best tool.

ProblemInputBest tool
Kth largest element in an arrayone fixed array, one questionquickselect, 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 onea size-k min-heap kept between calls, O(log k) per value
08

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.