Kth Largest Element in a Stream
Easy
Topics
Design a class to find the kth largest element in a stream (the kth largest in sorted order, not the kth distinct). Implement KthLargest(k, nums) which initializes with an integer k and a stream of integers nums, and add(val) which appends val and returns the kth largest element so far.
Example 1
Its root is then the kth largest, and each
add costs log k rather than a re-sort.Calls run top to bottom; the arrow shows what each one returns.
Input: operations = ["KthLargest","add","add","add","add","add"], values = [[3,4,5,8,2],[3],[5],[10],[9],[4]] Output: [null,4,5,5,8,8]
Constraints
- 1 <= k <= 10^4
- At least k elements exist when add is queried.
- At most 10^4 calls to add.
Editorial — intuition, approach, complexity and pitfalls
Intuition
You only ever need the k largest values seen so far; the kth largest is the smallest of those. A min-heap of size k keeps exactly them, with the answer sitting at its root.
Approach
- Push all initial numbers into a min-heap, then pop until only k remain.
- On add, push the new value; if the heap exceeds size k, pop the smallest.
- The heap root is the kth largest element.
Dry Run
KthLargest(3, [4, 5, 8, 2])
heapify [4, 5, 8, 2], then pop until only 3 remain -> heap [4, 5, 8]
the 2 is discarded; the root 4 is the 3rd largest of 4, 5, 8, 2
add 3 [4, 5, 8] push 3, size 4, pop the smallest (3) root 4
add 5 [4, 5, 8] push 5, pop the smallest (4) root 5
add 10 [5, 5, 8] push 10, pop the smallest (5) root 5
add 9 [5, 10, 8] push 9, pop the smallest (5) root 8
add 4 [8, 9, 10] push 4, pop the smallest (4) root 8
answer null|4|5|5|8|8
Adding 3 to a stream whose 3rd largest is already 4 should change nothing, and the
heap makes that cheap rather than special: 3 goes in and comes straight back out
as the smallest of the four.
It has to be a MIN-heap, which reads backwards until you see why. The heap holds
the k LARGEST values seen so far, so the smallest member of that set is the kth
largest overall -- and a min-heap keeps precisely that at its root, readable in
O(1). A max-heap would park the single biggest value on top and leave you walking
k - 1 entries per query.
Note what the heap never holds again: the 2 dropped during construction, and every
value later evicted. Once something falls out of the top k it can never return, so
throwing it away costs nothing.Complexity
- Time — O(log k) per add: each add does a heap push/pop bounded by size k.
- Space — O(k): the heap holds at most k elements.
Common Pitfalls
- Keep a min-heap (smallest on top), not a max-heap — the kth largest is the minimum of the top k.
Full Solution — all languages
class KthLargest:
def __init__(self, k, nums):
import heapq
self.k = k
self.heap = list(nums)
heapq.heapify(self.heap)
while len(self.heap) > k:
heapq.heappop(self.heap)
def add(self, val):
import heapq
heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap)
return self.heap[0]import java.util.*;
class KthLargest {
private final int k;
private final PriorityQueue<Integer> heap = new PriorityQueue<>();
public KthLargest(int k, int[] nums) {
this.k = k;
for (int v : nums) add(v);
}
public int add(int val) {
heap.offer(val);
if (heap.size() > k) heap.poll();
return heap.peek();
}
}#include <bits/stdc++.h>
using namespace std;
class KthLargest {
public: KthLargest(int k, vector<int>& nums) : k_(k) {
for (int v : nums) add(v);
}
int add(int val) {
heap_.push(val);
if ((int)heap_.size() > k_) heap_.pop();
return heap_.top();
}
private: int k_;
priority_queue<int, vector<int>, greater<int>> heap_;
};class KthLargest {
constructor(k, nums) {
// The stream is short here, so a kept-sorted array of the k largest is
// both simpler and fast enough; a binary heap is the scaling answer.
this.k = k;
this.top = nums.slice().sort((a, b) => a - b).slice(-k);
}
add(val) {
let i = 0;
while (i < this.top.length && this.top[i] < val) i++;
this.top.splice(i, 0, val);
if (this.top.length > this.k) this.top.shift();
return this.top[0];
}
}
Asked at
Adobe