Kth Largest Element in a Stream

Maintain the kth-largest under a streaming add() using a fixed-size min-heap.

Easy
Time O(log k) per add Space O(k)
LeetCode
4 min read
top-k heaps design

Problem#

Design KthLargest with add(int) returning the current kth-largest element after every insertion.

Examples#

  • k = 3, init = [4,5,8,2]; add(3) → 4; add(5) → 5; add(10) → 5; add(9) → 8; add(4) → 8

Constraints#

  • 1 <= k <= 10^4.

Approach#

Min-heap holding the k largest seen so far. Pushing keeps the heap size ≤ k by popping the smallest. The top is always the kth largest.

Solution#

Kth Largest in a Stream
class KthLargest {
priority_queue<int, vector<int>, greater<int>> pq;
int k;
public:
KthLargest(int k, vector<int>& nums) : k(k) {
for (int x : nums) add(x);
}
int add(int v) {
pq.push(v);
if ((int)pq.size() > k) pq.pop();
return pq.top();
}
};

Editorial#

A min-heap of size k is the canonical structure for “top k”: its top is the smallest of the kept k, which is exactly the kth-largest overall. Operations are O(log k).

Complexity#

  • Time: O(log k) per add.
  • Space: O(k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.