703. Kth Largest Element in a Stream
Problem
Design KthLargest(k, nums), initialised with a stream's first values; each add(val) appends a value and returns the k-th largest value seen so far.
Example: KthLargest(3, [4,5,8,2]) → add(3) = 4, add(5) = 5, add(10) = 5, add(9) = 8, add(4) = 8
Constraints: up to 10⁴ calls to add.
Min-heap of the k largest seen so far; its root is the answer.
Complexity: O(log k) per add.
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k, self.h = k, []
for x in nums:
self.add(x)
def add(self, val: int) -> int:
heappush(self.h, val)
if len(self.h) > self.k:
heappop(self.h)
return self.h[0]
kl = KthLargest(3, [4, 5, 8, 2])
assert [kl.add(v) for v in (3, 5, 10, 9, 4)] == [4, 5, 5, 8, 8]
kl = KthLargest(1, [])
assert [kl.add(v) for v in (-3, -2, -4, 0, 4)] == [-3, -2, -2, 0, 4]
class KthLargest {
private final PriorityQueue<Integer> pq = new PriorityQueue<>();
private final int k;
public KthLargest(int k, int[] nums) {
this.k = k;
for (int x : nums) add(x);
}
public int add(int val) {
pq.add(val);
if (pq.size() > k) pq.poll();
return pq.peek();
}
}
type IntHeap []int // min-heap
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
type KthLargest struct {
k int
h IntHeap // the k largest values; the root is the k-th largest
}
func Constructor(k int, nums []int) KthLargest {
kl := KthLargest{k: k}
for _, x := range nums {
kl.Add(x)
}
return kl
}
func (this *KthLargest) Add(val int) int {
heap.Push(&this.h, val)
if this.h.Len() > this.k {
heap.Pop(&this.h)
}
return this.h[0]
}