Given an unbounded stream and a small fixed memory budget, report approximately which items are most frequent. Implement your approach and state its error guarantee.
Answer
Model answer, written in a candidate's voice
In short
- Use fixed-memory heavy-hitter sketches; report estimates with explicit error, not exact counts.
- Misra-Gries: k counters, decrement all on a miss when full; estimate <= true count and true - estimate <= n/(k+1).
- Implementation: a dict of at most k counters, O(k) memory and O(k) worst-case work per item; a test checks c − n/(k+1) ≤ estimate ≤ c for every item.
- Count-Min: width ceil(e/eps), depth ceil(ln(1/delta)); estimate = min over rows; never underestimates; f_i <= est <= f_i + eps*n with probability >= 1-delta per query.
- Keep a size-k min-heap of candidates by estimate for top-k; refresh keys or accept stale estimates.
- Count-Min is linear and merges by summing counters for distributed streams; Misra-Gries is mergeable but less clean.
In full
I would treat this as approximate heavy hitters, not exact counting. With Misra-Gries I keep k (item,count) counters: increment on a hit, add on a miss if space remains, otherwise decrement every counter and drop zeros; the final estimate never exceeds the true frequency and is under by at most n/(k+1), so any item with frequency above n/(k+1) is guaranteed to appear. The bound holds because each decrement round removes k+1 occurrences (one from each of the k counters plus the arriving item), so there can be at most n/(k+1) such rounds. With Count-Min I use width ceil(e/eps) and depth ceil(ln(1/delta)), estimate each item as the minimum across rows, and keep a size-k min-heap of candidates by estimate; it only over-estimates, with f_i <= estimate <= f_i + eps*n with probability at least 1-delta for a query, though heap keys can go stale and should be refreshed or treated as approximate. For distributed streams, Count-Min is the clean choice because sketches with the same parameters merge by summing counters; Misra-Gries can be combined but is less trivial. In practice I would use Misra-Gries when I want a small candidate set with an underestimate guarantee, and Count-Min when I need mergeability and an over-estimate bound, reporting the guarantee alongside the top-k list.
A minimal Misra-Gries implementation, with a test that checks c − n/(k+1) ≤ estimate ≤ c for every item on a shuffled stream of 10,000 items:
import random
from collections import Counter
def misra_gries(stream, k):
"""Keep at most k counters. Each estimate is <= the true count and
undercounts by at most n/(k+1), where n is the stream length."""
counters = {}
for x in stream:
if x in counters:
counters[x] += 1
elif len(counters) < k:
counters[x] = 1
else: # decrement all k counters (and drop x)
for key in list(counters):
counters[key] -= 1
if counters[key] == 0:
del counters[key]
return counters
if __name__ == "__main__":
random.seed(0)
stream = (["a"] * 3000 + ["b"] * 2000 + ["c"] * 1000
+ [f"x{i}" for i in range(4000)]) # 4,000 singletons
random.shuffle(stream)
k, n = 9, len(stream)
est, true = misra_gries(stream, k), Counter(stream)
bound = n / (k + 1)
for item, c in true.items():
e = est.get(item, 0)
assert c - bound <= e <= c, (item, c, e)
if c > bound:
assert item in est # every item above n/(k+1) survives
print(sorted(est.items(), key=lambda kv: -kv[1])[:3], "bound", bound)What a strong answer covers
- Misra–Gries with k counters: each count is under by at most n/(k+1).
- Or a Count-Min sketch (only over-estimates, with ε/δ guarantees) plus a heap for the top-k.
- Sketches can be merged for distributed streams.
Common mistakes
- An exact hash map, which breaks the memory limit.
- No error bound.