Top-k, Heavy Hitters & Streaming Quantiles
Heaps for the k largest, Misra–Gries and quantile sketches.
A search engine wants today's 100 most frequent queries; a monitoring system wants the 99th-percentile latency over billions of requests. Neither can store its stream, yet a few kilobytes suffice: a heap for the largest items, a handful of counters for the most frequent ones, and a sketch that answers any quantile to within a fraction of a percent. This lesson proves what each of them guarantees, and where the limits are.
What you’ll learn
- Maintain the largest items of a stream with a size- min-heap, and prove that on a random-order stream only about items ever enter it.
- Find every item with frequency above in one pass with counters (Misra–Gries), and prove the error bound .
- Define -approximate quantiles, build a randomized compactor sketch, and explain its unbiased error.
- Compare quantile sketches by space (Greenwald–Khanna, KLL, beyond-comparison sketches) and state the lower bounds that make them optimal.
Top-k over a stream
To keep the largest items of a stream, the top-k problem, hold the best so far in a min-heap. Its root is the weakest of them, the bar a newcomer must clear: a smaller item costs one comparison and is forgotten, a larger one replaces the root in time. That is time in the worst case and memory, in one pass. Offline, with the whole array in memory, quickselect for rank followed by sorting the top costs only expected time.
import heapq
def top_k(stream, k):
"""The k largest items of a stream, in O(k) memory."""
heap = [] # min-heap of the best k so far; heap[0] is the weakest
for x in stream:
if len(heap) < k:
heapq.heappush(heap, x)
elif x > heap[0]: # x beats the weakest of the current top k
heapq.heapreplace(heap, x)
return sorted(heap, reverse=True)top_k([42, 17, 63, 8, 91, 55, 30], 3) returns [91, 63, 55]. Python's heapq.nlargest works the same way.
The -th arrival, for , enters the heap exactly when it is among the largest of the first arrivals. In a random order each of those items is equally likely to be the last of them to arrive, so
Add the first arrivals, which always enter, and sum by linearity of expectation:
For and this is about 790 entries out of arrivals; twenty simulated random streams averaged 793. Adversarial order (increasing items) makes every arrival enter, which is the worst case.
Heavy hitters: Misra–Gries
Now count frequencies. The heavy hitters of a stream of items are those occurring more than times; there are fewer than of them. Finding them exactly in one pass needs memory that grows with the stream, but a small summary can come close. The Misra–Gries algorithm (1982) keeps at most counters and treats a full table like a bargaining table: an item with no counter cancels one occurrence of every counted item, and itself.
def misra_gries(stream, k):
"""At most k - 1 counters. Every item with frequency > n/k keeps a counter,
and each counter undercounts its item by at most n/k."""
counters = {}
for x in stream:
if x in counters:
counters[x] += 1
elif len(counters) < k - 1:
counters[x] = 1
else: # no room: cancel x against one occurrence of every counted item
for y in list(counters):
counters[y] -= 1
if counters[y] == 0:
del counters[y]
return counters
print(misra_gries("abacabadabacabae", 3)) # {'a': 4}; the true count of 'a' is 8Tested on random streams against exact counts. With it keeps one counter: the Boyer–Moore majority vote (1981), which finds an item occurring more than times if there is one.
Counters grow only when their own item arrives, so . Each cancellation step (an arrival meeting a full table) removes units of count: the arriving item, never counted, and one unit from each of the counters. Every other arrival adds one unit. So with cancellation steps,
In each cancellation step, item loses at most one unit: either its counter is decremented, or the arriving item is and goes uncounted. Hence
If , then : keeps a counter. In the example, , and , so , and the counter of 'a' is exactly .
A router must report every destination that receives more than 1% of the day's packets, using little memory, and it can replay the day's log once more at night. Which plan fits?
- Keep a size-100 heap of the largest packets
- Misra–Gries with 99 counters during the day, then one more pass to count the surviving candidates exactly
- An exact hash map from every destination to its count
- Count a random 1% sample of the packets
Show the answer
B. Misra–Gries with 99 counters during the day, then one more pass to count the surviving candidates exactly
With , Misra–Gries guarantees that every destination above survives among at most 99 candidates. The candidates may include false positives, and their counts are underestimates, so the night pass counts just those 99 destinations exactly and keeps the ones truly above 1%.
Streaming quantiles
The rank of a value is the number of stream items . An -approximate quantile summary answers every rank query within ; asked for the -quantile, it returns an item whose rank is within of . Exactness is out of reach: computing the exact median in one pass requires storing essentially the whole stream (Munro & Paterson, 1980).
A quantile sketch trades exactness for size. The simplest good one is a stack of compactors: level holds items that each stand for original items, and when a level fills up, it is sorted and every other item moves up a level with doubled weight.
import random
class Compactors:
"""A tiny randomized quantile sketch: level h holds items of weight 2**h."""
def __init__(self, cap):
self.cap, self.levels = cap, [[]]
def add(self, x):
self.levels[0].append(x)
h = 0
while len(self.levels[h]) >= self.cap: # level h is full: compact it
buf = sorted(self.levels[h])
if h + 1 == len(self.levels):
self.levels.append([])
self.levels[h + 1].extend(buf[random.randint(0, 1)::2]) # keep every other item
self.levels[h] = []
h += 1
def rank(self, x): # estimated number of items <= x
return sum(2 ** h * sum(y <= x for y in lev) for h, lev in enumerate(self.levels))With capacity 200 and random numbers, the sketch stored 600 items. Over 20 runs, its rank estimates for the 19 quantiles at 5%, 10%, …, 95% were never off by more than 0.83% of .
One compaction is unbiased. Suppose items of a level- buffer are . After keeping every other item from a random offset, those items are represented by or survivors of weight : no error when is even, and with equal probability when is odd.
Errors add like a random walk. With capacity , level is compacted about times, and the compactions use independent coins. Summing variances over the levels, the top level dominates:
So the error has standard deviation about , and gives error with constant probability, in space. KLL (Karnin, Lang & Liberty, 2016) shrinks the capacities of the lower levels geometrically, because their errors weigh little, and reaches error with probability in
| Sketch | Space | Guarantee |
|---|---|---|
| Greenwald–Khanna (2001) | items | deterministic; optimal among deterministic comparison-based summaries (Cormode & Veselý, 2020) |
| KLL (2016) | items | randomized, error at most with probability per query; optimal |
| Gupta, Singhal & Wu (2024) | words | deterministic, for integers from with ; beats the comparison-based bound |
| t-digest (Dunning & Ertl, 2019) | small, tunable | very accurate near the extremes in practice; no comparable worst-case guarantee |
Variants, and what is still open
Space-Saving (Metwally, Agrawal & El Abbadi, 2005) is Misra–Gries's mirror image: it keeps counters, and an unmonitored item replaces the item with the smallest counter, inheriting that count plus one. Counts become overestimates, by at most the smallest counter, which is at most , and the order of its counters answers top- queries directly; it is a favorite in practice.
When items can also be deleted, or arrive with weights, counter-based summaries break, and hashing takes over: Count-Min and related sketches estimate every frequency from a few hashed counters (see Count-Min, HyperLogLog & Streaming Sketches).
Key takeaways
- A size- min-heap keeps the largest items of a stream in worst-case time and memory; on a random-order stream only items ever enter it.
- Misra–Gries keeps counters, undercounts every item by at most , and so never loses an item with frequency above ; Boyer–Moore majority vote is the case , and a second pass removes false positives.
- Exact one-pass quantiles need memory proportional to the stream; -approximate ones do not. Randomized compactors halve sorted buffers with random offsets, so their errors are unbiased and cancel.
- Space for -quantiles: for deterministic comparison-based summaries (Greenwald–Khanna, optimal), randomized (KLL, optimal), and words for bounded integer universes (2024).
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
You keep the 100 largest of streamed readings with a size-100 min-heap. What are the worst-case time and the memory?
- time and memory, as for sorting
- time and memory
- time and memory for 100 readings
- time and memory for 100 readings
Show the answer
C. time and memory for 100 readings
Each reading costs one comparison with the root, plus when it replaces the root, which in the worst case (increasing readings) happens every time. Memory holds just the 100 current winners.
Misra–Gries with 9 counters () processes items. Which guarantee holds?
- Every item that occurs more than times ends with a counter, and every counter undercounts its item by at most
- The 9 counters hold exactly the 9 most frequent items
- Every counter overcounts its item by at most
- Every item with a counter occurs more than times
Show the answer
A. Every item that occurs more than times ends with a counter, and every counter undercounts its item by at most
At most cancellation steps happen, and each costs any item at most one unit, so counts are undercounts by at most , and an item above the threshold cannot be cancelled down to zero.
In the compactor sketch, why does each compaction keep every other item starting from a random offset, rather than always the even positions?
- To make the sketch faster
- So that each compaction's rank error is or with equal probability: unbiased, and the errors of many compactions cancel like a random walk
- Because sorting would otherwise fail on equal items
- It makes no difference to the error
Show the answer
B. So that each compaction's rank error is or with equal probability: unbiased, and the errors of many compactions cancel like a random walk
A fixed offset errs in the same direction every time, so the errors add up linearly over the compactions. With a random offset the errors have mean zero and are independent, so they grow only like the square root of their summed variances, about in total.
Which statement about one-pass -approximate quantile summaries is correct?
- Deterministic comparison-based summaries need space, and Greenwald–Khanna achieves it, while randomized KLL needs only
- Every summary needs space, as exact selection does
- space suffices for every algorithm and every input type
- Randomized summaries cannot beat deterministic ones
Show the answer
A. Deterministic comparison-based summaries need space, and Greenwald–Khanna achieves it, while randomized KLL needs only
Cormode and Veselý (2020) proved that no deterministic comparison-based summary uses less than about space, so Greenwald–Khanna is optimal. Randomization removes the dependence on (KLL), and using the items' bits removes it deterministically for integer universes (Gupta, Singhal & Wu, 2024).
Further reading
- J. Misra & D. Gries, "Finding repeated elements," Science of Computer Programming 2(2) (1982), 143–152.
- M. Greenwald & S. Khanna, "Space-efficient online computation of quantile summaries," Proceedings of ACM SIGMOD (2001), 58–66.
- Z. Karnin, K. Lang & E. Liberty, "Optimal quantile approximation in streams," Proceedings of the 57th IEEE Symposium on Foundations of Computer Science (2016), 71–78.
- M. Gupta, M. Singhal & H. Wu, "Optimal quantile estimation: beyond the comparison model," Proceedings of the 65th IEEE Symposium on Foundations of Computer Science (2024), 1137–1158.
- G. Cormode & K. Yi, Small Summaries for Big Data (Cambridge University Press, 2020).