Approach: For a single-pass approximate k-th smallest on a massive stream, two practical sketches are: (1) a max-heap of size m (memory budget) that keeps the m smallest seen values — if m >= k the heap's root approximates k-th smallest; (2) randomized reservoir sampling + exact selection on the sample. Trade-offs: larger m improves accuracy but uses more memory; sampling reduces memory/time but loses rare small values (bias). Heaps give monotonic guarantees (never miss values smaller than kept), sampling gives unbiased estimation of distribution.Heap-based sketch (preferred when you can store m elements, m >= k recommended):python
import heapq
def kth_smallest_stream_heap(stream, k, m):
"""
Keep a max-heap (store negatives) of up to m smallest elements.
Return heap_root as approximate k-th smallest (if m>=k, closer to true).
"""
if m < 1: raise ValueError("m must be >=1")
max_heap = [] # will store negatives to simulate max-heap
for x in stream: # stream yields integers
if len(max_heap) < m:
heapq.heappush(max_heap, -x)
elif x < -max_heap[0]:
heapq.heapreplace(max_heap, -x)
if len(max_heap) < k:
return None # sample too small to estimate k-th
# approximate k-th: sort kept elements and pick k-th
kept = sorted([-v for v in max_heap])
return kept[k-1]
Sampling-based sketch:python
import random
def kth_smallest_stream_sample(stream, k, m):
"""
Reservoir sample m items, then compute exact k-th on the sample.
Good when memory m << stream size; variance decreases with m.
"""
sample = []
for i, x in enumerate(stream, start=1):
if i <= m:
sample.append(x)
else:
j = random.randint(1, i)
if j <= m:
sample[j-1] = x
if len(sample) < k: return None
sample.sort()
return sample[k-1]
Complexity:- Heap: O(n log m) time, O(m) memory. Accuracy increases with m; if m = k exact if no smaller items were evicted.- Sampling: O(n) time to sample (O(m log m) final sort), O(m) memory. Accuracy depends on sample representativeness (variance ~1/m).Edge cases:- m < k (cannot guarantee); highly skewed distributions where rare very small values may be missed.- Stream with duplicates—both handle duplicates naturally.Alternatives: quantile sketches (t-digest, GK) provide probabilistic error bounds for rank queries and are better when you need guaranteed rank error bounds. Use them for stricter accuracy-memory trade-offs.