k-th largest in a stream
Problem
Start from the values in initial. After inserting each value of adds (in order), report the k-th largest value seen so far, counting duplicates separately, or None if fewer than k values have been seen.
Signature
def kth_largest_stream(k: int, initial: list[int], adds: list[int]) -> list[int | None]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> kth_largest_stream(3, [4, 5, 8, 2], [3, 5, 10, 9, 4]) == [4, 5, 5, 8, 8]
True
>>> kth_largest_stream(1, [], [-1, 1, -2]) == [-1, 1, 1]
TrueHints
Keep a min-heap capped at k values; O(log k) per insert.
After each add, report the heap root (the k-th largest) or None if fewer than k exist.
Count duplicates separately — not the k-th distinct value.
Reference solution
import heapq
def kth_largest_stream(k, initial, adds):
h = []
def push(x):
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h)
for x in initial:
push(x)
out = []
for x in adds:
push(x)
out.append(h[0] if len(h) == k else None)
return outWhat a strong solution covers
- Min-heap capped at size k, O(log k) per insert.
- Handles fewer than k values.
- Discusses top-k with deletions and approximate heavy hitters (Count-Min sketch).
Common mistakes
- a max-heap holding all values (O(n) memory)
- returning the k-th distinct value.