Kth Largest Element in a Stream
Difficulty: Easy · Pattern: Heap & Priority Queue · LeetCode #703
Design a class that is constructed with an integer k and an initial list nums, and supports add(val): insert val into the stream and return the k-th largest value seen so far. It's guaranteed that at least k values exist whenever you're asked.
Example
text
KthLargest(3, [4, 5, 8, 2])
add(3) → 4, add(5) → 5, add(10) → 5, add(9) → 8, add(4) → 8Hints
- You only ever need the k largest values; everything smaller is irrelevant forever.
- Keep a min-heap of size k; the answer is its root.
Approach
Keep a min-heap of at most k values. In the constructor, add all initial numbers (popping when the size exceeds k). For add(val), push it, pop if the size exceeds k, and return the root. Each add is O(log k).
Complexity
Time: O(log k) per add (O(n log k) to build). Space: O(k).
Python solution
import heapq
class KthLargest:
def __init__(self, k, nums):
self.k, self.h = k, []
for x in nums:
self.add(x)
def add(self, val):
heapq.heappush(self.h, val)
if len(self.h) > self.k:
heapq.heappop(self.h)
return self.h[0]JavaScript solution
class MinHeap {
constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
get size() { return this.a.length; }
peek() { return this.a[0]; }
push(x) { const a = this.a; a.push(x); let i = a.length - 1;
while (i > 0) { const p = (i - 1) >> 1; if (this.cmp(a[i], a[p]) >= 0) break; [a[i], a[p]] = [a[p], a[i]]; i = p; } }
pop() { const a = this.a, top = a[0], last = a.pop();
if (a.length) { a[0] = last; let i = 0;
for (;;) { const l = 2 * i + 1, r = l + 1; let m = i;
if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
if (m === i) break; [a[i], a[m]] = [a[m], a[i]]; i = m; } }
return top; }
}
class KthLargest {
constructor(k, nums) { this.k = k; this.h = new MinHeap(); for (const x of nums) this.add(x); }
add(val) { this.h.push(val); if (this.h.size > this.k) this.h.pop(); return this.h.peek(); }
}