703. Kth Largest Element in a Stream
Easy NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Heap / Priority Queue
- Time
- O(log k) per add
- Space
- O(k)
Standard Solution (C++)
SummaryBuild a structure that, as numbers are added one at a time, can always report the k-th largest value seen so far.
Approach
Min-heap of size k. Keep a min-heap holding only the k largest elements seen so far.
- On each add, push the new value, then pop while the heap size exceeds k.
- The heap top is then the k-th largest element, which we return.
This keeps every operation cheap and avoids re-sorting the whole stream.
class KthLargest {
priority_queue<int, vector<int>, greater<int>> minHeap;
int k;
public:
KthLargest(int k, vector<int>& nums) : k(k) {
for (int x : nums) add(x);
}
int add(int val) {
minHeap.push(val);
while ((int)minHeap.size() > k) minHeap.pop();
return minHeap.top();
}
}; Time O(log k) per add Space O(k)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground C++
Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.
C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.