Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 kk largest items of a stream with a size-kk min-heap, and prove that on a random-order stream only about kln⁡(n/k)k \ln(n/k) items ever enter it.
  • Find every item with frequency above n/kn/k in one pass with k−1k - 1 counters (Misra–Gries), and prove the error bound n/kn/k.
  • Define ε\varepsilon-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 kk largest items of a stream, the top-k problem, hold the best kk 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 O(log⁡k)O(\log k) time. That is O(nlog⁡k)O(n \log k) time in the worst case and O(k)O(k) memory, in one pass. Offline, with the whole array in memory, quickselect for rank n−kn - k followed by sorting the top kk costs only O(n+klog⁡k)O(n + k \log k) expected time.

python
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.

DerivationProof
  1. Pr⁡[arrival i enters]=ki(i>k)\Pr[\text{arrival } i \text{ enters}] = \frac{k}{i} \qquad (i > k)

    The ii-th arrival, for i>ki > k, enters the heap exactly when it is among the kk largest of the first ii arrivals. In a random order each of those ii items is equally likely to be the last of them to arrive, so

  2. E[entries]=k+∑i=k+1nki=k (1+Hn−Hk)≈k(1+ln⁡nk)\E[\text{entries}] = k + \sum_{i = k+1}^{n} \frac{k}{i} = k\,(1 + H_n - H_k) \approx k\left(1 + \ln \frac{n}{k}\right)

    Add the first kk arrivals, which always enter, and sum by linearity of expectation:

  3. 100 (1+H105−H100)≈790100\,(1 + H_{10^5} - H_{100}) \approx 790

    For n=105n = 10^5 and k=100k = 100 this is about 790 entries out of 10510^5 arrivals; twenty simulated random streams averaged 793. Adversarial order (increasing items) makes every arrival enter, which is the O(nlog⁡k)O(n \log k) worst case.

Heavy hitters: Misra–Gries

Now count frequencies. The heavy hitters of a stream of nn items are those occurring more than n/kn/k times; there are fewer than kk 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 k−1k - 1 counters and treats a full table like a bargaining table: an item with no counter cancels one occurrence of every counted item, and itself.

python
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 8

Tested on random streams against exact counts. With k=2k = 2 it keeps one counter: the Boyer–Moore majority vote (1981), which finds an item occurring more than n/2n/2 times if there is one.

DerivationProof: count the cancellations
  1. m=n−k d⟹d=n−mk≤nkm = n - k\,d \quad\Longrightarrow\quad d = \frac{n - m}{k} \le \frac{n}{k}

    Counters grow only when their own item arrives, so f^x≤fx\hat f_x \le f_x. Each cancellation step (an arrival meeting a full table) removes kk units of count: the arriving item, never counted, and one unit from each of the k−1k - 1 counters. Every other arrival adds one unit. So with dd cancellation steps,

  2. f^x  ≥  fx−d  =  fx−n−mk\hat f_x \;\ge\; f_x - d \;=\; f_x - \frac{n - m}{k}

    In each cancellation step, item xx loses at most one unit: either its counter is decremented, or the arriving item is xx and goes uncounted. Hence

  3. fx>nk  ⟹  f^x>0f_x > \frac{n}{k} \;\Longrightarrow\; \hat f_x > 0

    If fx>n/k≥df_x > n/k \ge d, then f^x>0\hat f_x > 0: xx keeps a counter. In the example, n=16n = 16, k=3k = 3 and m=4m = 4, so d=4d = 4, and the counter of 'a' is exactly 8−4=48 - 4 = 4.

Check your understanding

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?

  1. Keep a size-100 heap of the largest packets
  2. Misra–Gries with 99 counters during the day, then one more pass to count the surviving candidates exactly
  3. An exact hash map from every destination to its count
  4. 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 k=100k = 100, Misra–Gries guarantees that every destination above n/100n/100 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 xx is the number of stream items ≤x\le x. An ε\varepsilon-approximate quantile summary answers every rank query within ±εn\pm \varepsilon n; asked for the qq-quantile, it returns an item whose rank is within εn\varepsilon n of qnqn. 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 hh holds items that each stand for 2h2^h original items, and when a level fills up, it is sorted and every other item moves up a level with doubled weight.

python
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 10510^5 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 nn.

DerivationWhy the error is small
  1. error∈{−2h, 0, +2h},E[error]=0\text{error} \in \{-2^h,\ 0,\ +2^h\}, \qquad \E[\text{error}] = 0

    One compaction is unbiased. Suppose cc items of a level-hh buffer are ≤x\le x. After keeping every other item from a random offset, those cc items are represented by ⌊c/2⌋\lfloor c/2 \rfloor or ⌈c/2⌉\lceil c/2 \rceil survivors of weight 2h+12^{h+1}: no error when cc is even, and ±2h\pm 2^h with equal probability when cc is odd.

  2. Var⁡[rank error]  ≤  ∑hnB 2h⋅4h  =  nB∑h2h  ≈  (nB)2\Var[\text{rank error}] \;\le\; \sum_h \frac{n}{B\,2^h} \cdot 4^h \;=\; \frac{n}{B} \sum_h 2^h \;\approx\; \left(\frac{n}{B}\right)^2

    Errors add like a random walk. With capacity BB, level hh is compacted about n/(B 2h)n/(B\,2^h) times, and the compactions use independent coins. Summing variances over the log⁡2(n/B)\log_2(n/B) levels, the top level dominates:

  3. O ⁣(1εlog⁡log⁡1δ) space, with a matching lower boundO\!\left(\frac{1}{\varepsilon} \log \log \frac{1}{\delta}\right) \text{ space, with a matching lower bound}

    So the error has standard deviation about n/Bn/B, and B≈1/εB \approx 1/\varepsilon gives error εn\varepsilon n with constant probability, in O(1εlog⁡(εn))O(\tfrac1\varepsilon \log(\varepsilon n)) space. KLL (Karnin, Lang & Liberty, 2016) shrinks the capacities of the lower levels geometrically, because their errors weigh little, and reaches error εn\varepsilon n with probability 1−δ1 - \delta in

SketchSpaceGuarantee
Greenwald–Khanna (2001)O(1εlog⁡(εn))O(\tfrac1\varepsilon \log(\varepsilon n)) itemsdeterministic; optimal among deterministic comparison-based summaries (Cormode & Veselý, 2020)
KLL (2016)O(1εlog⁡log⁡1δ)O(\tfrac1\varepsilon \log\log \tfrac1\delta) itemsrandomized, error at most εn\varepsilon n with probability 1−δ1 - \delta per query; optimal
Gupta, Singhal & Wu (2024)O(1ε)O(\tfrac1\varepsilon) wordsdeterministic, for integers from {1,…,U}\{1, \dots, U\} with n≤poly⁡(U)n \le \poly(U); beats the comparison-based bound
t-digest (Dunning & Ertl, 2019)small, tunablevery accurate near the extremes in practice; no comparable worst-case guarantee
Comparison-based summaries may only compare items; the 2024 sketch also uses the items' bits, which is how it escapes the Ω(1εlog⁡(εn))\Omega(\tfrac1\varepsilon \log(\varepsilon n)) lower bound.

Variants, and what is still open

Space-Saving (Metwally, Agrawal & El Abbadi, 2005) is Misra–Gries's mirror image: it keeps kk 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 n/kn/k, and the order of its counters answers top-kk 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-kk min-heap keeps the kk largest items of a stream in O(nlog⁡k)O(n \log k) worst-case time and O(k)O(k) memory; on a random-order stream only k(1+Hn−Hk)≈kln⁡(n/k)k(1 + H_n - H_k) \approx k \ln(n/k) items ever enter it.
  • Misra–Gries keeps k−1k - 1 counters, undercounts every item by at most (n−m)/k≤n/k(n - m)/k \le n/k, and so never loses an item with frequency above n/kn/k; Boyer–Moore majority vote is the case k=2k = 2, and a second pass removes false positives.
  • Exact one-pass quantiles need memory proportional to the stream; ε\varepsilon-approximate ones do not. Randomized compactors halve sorted buffers with random offsets, so their errors are unbiased and cancel.
  • Space for ε\varepsilon-quantiles: Θ(1εlog⁡(εn))\Theta(\tfrac1\varepsilon \log(\varepsilon n)) for deterministic comparison-based summaries (Greenwald–Khanna, optimal), O(1εlog⁡log⁡1δ)O(\tfrac1\varepsilon \log\log\tfrac1\delta) randomized (KLL, optimal), and O(1ε)O(\tfrac1\varepsilon) 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.

Question 1

You keep the 100 largest of 10910^9 streamed readings with a size-100 min-heap. What are the worst-case time and the memory?

  1. O(nlog⁡n)O(n \log n) time and O(n)O(n) memory, as for sorting
  2. O(n)O(n) time and O(1)O(1) memory
  3. O(nlog⁡100)O(n \log 100) time and memory for 100 readings
  4. O(100log⁡n)O(100 \log n) time and memory for 100 readings
Show the answer

C. O(nlog⁡100)O(n \log 100) time and memory for 100 readings

Each reading costs one comparison with the root, plus O(log⁡100)O(\log 100) when it replaces the root, which in the worst case (increasing readings) happens every time. Memory holds just the 100 current winners.

Question 2

Misra–Gries with 9 counters (k=10k = 10) processes n=106n = 10^6 items. Which guarantee holds?

  1. Every item that occurs more than 10510^5 times ends with a counter, and every counter undercounts its item by at most 10510^5
  2. The 9 counters hold exactly the 9 most frequent items
  3. Every counter overcounts its item by at most 10510^5
  4. Every item with a counter occurs more than 10510^5 times
Show the answer

A. Every item that occurs more than 10510^5 times ends with a counter, and every counter undercounts its item by at most 10510^5

At most n/k=105n/k = 10^5 cancellation steps happen, and each costs any item at most one unit, so counts are undercounts by at most 10510^5, and an item above the threshold cannot be cancelled down to zero.

Question 3

In the compactor sketch, why does each compaction keep every other item starting from a random offset, rather than always the even positions?

  1. To make the sketch faster
  2. So that each compaction's rank error is +2h+2^h or −2h-2^h with equal probability: unbiased, and the errors of many compactions cancel like a random walk
  3. Because sorting would otherwise fail on equal items
  4. It makes no difference to the error
Show the answer

B. So that each compaction's rank error is +2h+2^h or −2h-2^h 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 n/Bn/B in total.

Question 4

Which statement about one-pass ε\varepsilon-approximate quantile summaries is correct?

  1. Deterministic comparison-based summaries need Θ(1εlog⁡(εn))\Theta(\tfrac1\varepsilon \log(\varepsilon n)) space, and Greenwald–Khanna achieves it, while randomized KLL needs only O(1εlog⁡log⁡1δ)O(\tfrac1\varepsilon \log\log\tfrac1\delta)
  2. Every summary needs Ω(n)\Omega(n) space, as exact selection does
  3. O(1ε)O(\tfrac1\varepsilon) space suffices for every algorithm and every input type
  4. Randomized summaries cannot beat deterministic ones
Show the answer

A. Deterministic comparison-based summaries need Θ(1εlog⁡(εn))\Theta(\tfrac1\varepsilon \log(\varepsilon n)) space, and Greenwald–Khanna achieves it, while randomized KLL needs only O(1εlog⁡log⁡1δ)O(\tfrac1\varepsilon \log\log\tfrac1\delta)

Cormode and Veselý (2020) proved that no deterministic comparison-based summary uses less than about 1εlog⁡(εn)\tfrac1\varepsilon \log(\varepsilon n) space, so Greenwald–Khanna is optimal. Randomization removes the dependence on nn (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).