Misra-Gries and the Majority Vote
The heavy hitters of a stream are the items that occur often: the pages that get most of the traffic, the source addresses behind most of the packets, the queries that dominate a log. Formally, for , the -heavy hitters of an insertion-only stream of length are the items with . There are fewer than of them, so a small output, but finding them exactly in one pass needs space. The fix is an additive error, and the oldest and still one of the best algorithms for it is deterministic: Misra and Gries (1982) keep counters and estimate every frequency to within .
The majority vote:
The simplest case asks for a majority element, one with , if there is one. Boyer and Moore (1981) solved it with one candidate and one counter:
Majority vote (Boyer-Moore)
1 cand ← none; c ← 0
2 for each item x:
3 if c = 0: cand ← x; c ← 1
4 else if x = cand: c ← c + 1
5 else: c ← c − 1
6 report cand (the majority, if one exists; check with a second pass)Think of each decrement as cancelling the incoming item against one copy of the candidate: two different items disappear together. A majority element has more copies than all other items combined, so it cannot be cancelled completely and must be the candidate at the end. If no majority exists, the candidate is arbitrary, which is why a second pass (or a count kept alongside) must confirm it. This is the practice problem Majority Element.
Misra-Gries with counters
Misra-Gries generalizes the cancellation: keep up to (item, count) pairs, and when a new item arrives while all counters are taken, cancel distinct items at once, the newcomer and one copy of each counted item.
Misra-Gries summary with k − 1 counters
1 C ← empty map item → count
2 for each item x:
3 if x ∈ C: C[x] ← C[x] + 1
4 else if |C| < k − 1: C[x] ← 1
5 else:
6 for each y ∈ C: C[y] ← C[y] − 1; remove y if C[y] = 0
7 (x itself is not stored)
8 estimate of f_x: C[x] if x ∈ C, else 0With it is exactly the majority vote. The animation runs it with (two counters) on a stream of 12 items.
The program prints the same trace and compares the final estimates with the true counts.
from collections import Counter
def misra_gries(stream, k, trace=False):
"""k - 1 counters, kept as a list of [item, count] in the order they were created."""
C = []
for t, x in enumerate(stream, 1):
hit = next((c for c in C if c[0] == x), None)
if hit:
hit[1] += 1
what = f"{x} has a counter, increment"
elif len(C) < k - 1:
C.append([x, 1])
what = f"{x} is new, free counter"
else:
for c in C:
c[1] -= 1
gone = [c[0] for c in C if c[1] == 0]
C = [c for c in C if c[1] > 0]
what = f"{x} is new, all taken: decrement all" + (f", drop {', '.join(gone)}" if gone else "")
if trace:
print(f"{t:2} {x}: {' '.join(f'{a}={b}' for a, b in C):12} {what}")
return {a: b for a, b in C}
stream = "a b a c a d b a e b a b".split()
est = misra_gries(stream, 3, trace=True)
true = Counter(stream)
m, k = len(stream), 3
print(f"m = {m}, k = {k}: every estimate is in [f - m/k, f] = [f - {m / k:.1f}, f]")
for x in sorted(true):
print(f" {x}: true {true[x]}, estimate {est.get(x, 0)}") 1 a: a=1 a is new, free counter
2 b: a=1 b=1 b is new, free counter
3 a: a=2 b=1 a has a counter, increment
4 c: a=1 c is new, all taken: decrement all, drop b
5 a: a=2 a has a counter, increment
6 d: a=2 d=1 d is new, free counter
7 b: a=1 b is new, all taken: decrement all, drop d
8 a: a=2 a has a counter, increment
9 e: a=2 e=1 e is new, free counter
10 b: a=1 b is new, all taken: decrement all, drop e
11 a: a=2 a has a counter, increment
12 b: a=2 b=1 b is new, free counter
m = 12, k = 3: every estimate is in [f - m/k, f] = [f - 4.0, f]
a: true 5, estimate 2
b: true 4, estimate 1
c: true 1, estimate 0
d: true 1, estimate 0
e: true 1, estimate 0
The guarantee
Theorem (Misra and Gries, 1982). Let be the estimate after an insertion-only stream of length , and let be the sum of the counters at the end. Then for every item
In particular , so every item with has a counter at the end.
Proof. The upper bound is clear: only grows when arrives. For the lower bound, call a run of line 6 a decrement step. In a decrement step units of count disappear: one from each of the counters and the arriving item, which is never counted. All other steps add exactly 1 to the total of the counters. So if is the number of decrement steps, , that is . Each occurrence of that is not reflected in was lost in a decrement step (either 's counter was decremented, or arrived and was dropped), and each decrement step loses at most one occurrence of . Hence .
The trace above shows the bound is tight: there were decrement steps, , and both a and b lost exactly 3 occurrences.
Space and time. The summary uses items and counters, words, independent of and . A decrement step costs , but there are at most of them, so the amortized time per item is plus the dictionary lookup; with a careful structure (counters grouped by value in a linked list) every step is in the worst case.
Lower bound. Any one-pass algorithm with additive error less than for every item needs words in the worst case, so Misra-Gries is optimal up to constant factors (a counting argument over streams with items of frequency about ; see Bose, Kranakis, Morin and Tang, 2003, for the precise statement).
Finding the heavy hitters
To report the -heavy hitters, run Misra-Gries with : every item with survives. The survivors may include false positives, which can be removed in two ways:
- a second pass that counts the at most candidates exactly;
- one pass with a slack: run with and report items with . Every item with is reported and no item with is, which is the usual -approximate heavy hitters guarantee.
The program runs Misra-Gries on 100 000 Zipf-distributed items for three values of and checks the theorem against exact counts.
import random
from collections import Counter
def misra_gries(stream, k):
C = {}
for x in stream:
if x in C:
C[x] += 1
elif len(C) < k - 1:
C[x] = 1
else:
for y in list(C):
C[y] -= 1
if C[y] == 0:
del C[y]
return C
rng = random.Random(1982)
U = 50000
cum, s = [], 0.0
for i in range(U):
s += 1 / (i + 1) ** 1.1
cum.append(s)
stream = rng.choices(range(U), cum_weights=cum, k=100000)
true = Counter(stream)
m = len(stream)
for k in [10, 50, 200]:
C = misra_gries(stream, k)
m_left = sum(C.values())
worst = max(true[x] - C.get(x, 0) for x in true)
heavy = [x for x in true if true[x] > m / k]
print(f"k = {k:3}: {len(C):3} counters in use, largest undercount {worst:5}, "
f"(m - m')/k = {(m - m_left) / k:7.1f}, m/k = {m / k:6.0f}; "
f"{len(heavy):2} items above m/k, all kept: {all(x in C for x in heavy)}")
C = misra_gries(stream, 50) # second pass: exact counts of the candidates
exact = Counter(x for x in stream if x in C)
print("second pass, k = 50: candidates really above m/50 =", sorted(x for x in C if exact[x] > m / 50))k = 10: 8 counters in use, largest undercount 9552, (m - m')/k = 9554.0, m/k = 10000; 1 items above m/k, all kept: True
k = 50: 45 counters in use, largest undercount 1541, (m - m')/k = 1541.0, m/k = 2000; 5 items above m/k, all kept: True
k = 200: 56 counters in use, largest undercount 303, (m - m')/k = 303.0, m/k = 500; 19 items above m/k, all kept: True
second pass, k = 50: candidates really above m/50 = [0, 1, 2, 3, 4]
In each case the worst undercount sits right at , which is noticeably smaller than because the counters still hold part of the stream. Every item above was kept. The summary for uses only 56 of its 199 counters at the end, though all were used during the run.
In C++
The same summary with std::unordered_map, run on a million skewed items (item with probability , mixed with uniform noise over items), with .
#include <algorithm>
#include <bit>
#include <cstdint>
#include <cstdio>
#include <random>
#include <unordered_map>
#include <vector>
class MisraGries {
std::size_t k;
std::unordered_map<std::uint64_t, std::uint64_t> C;
public:
explicit MisraGries(std::size_t k) : k(k) { C.reserve(2 * k); }
void add(std::uint64_t x) {
if (auto it = C.find(x); it != C.end()) { ++it->second; return; }
if (C.size() < k - 1) { C.emplace(x, 1); return; }
for (auto it = C.begin(); it != C.end();) // decrement step: cancel k distinct items
if (--it->second == 0) it = C.erase(it); else ++it;
}
std::uint64_t estimate(std::uint64_t x) const { auto it = C.find(x); return it == C.end() ? 0 : it->second; }
std::uint64_t total() const { std::uint64_t s = 0; for (auto& [x, c] : C) s += c; return s; }
};
int main() {
std::mt19937_64 rng(1982);
const std::uint64_t m = 1000000, k = 20;
MisraGries mg(k);
std::unordered_map<std::uint64_t, std::uint64_t> exact;
for (std::uint64_t t = 0; t < m; ++t) {
std::uint64_t r = rng();
std::uint64_t x = (r & 3) ? std::countr_zero(r >> 2) : (r >> 8) % 100000;
mg.add(x);
++exact[x];
}
std::uint64_t worst = 0;
for (auto [x, f] : exact) worst = std::max(worst, f - mg.estimate(x));
std::printf("m = %llu, k = %llu: largest undercount %llu, (m - m')/k = %llu, m/k = %llu\n",
(unsigned long long)m, (unsigned long long)k, (unsigned long long)worst,
(unsigned long long)((m - mg.total()) / k), (unsigned long long)(m / k));
for (std::uint64_t x = 0; x < 5; ++x)
std::printf("item %llu: true %7llu, estimate %7llu\n", (unsigned long long)x,
(unsigned long long)exact[x], (unsigned long long)mg.estimate(x));
}m = 1000000, k = 20: largest undercount 18266, (m - m')/k = 18266, m/k = 50000
item 0: true 375177, estimate 356911
item 1: true 187098, estimate 168832
item 2: true 93742, estimate 75476
item 3: true 46443, estimate 28177
item 4: true 23535, estimate 5269
Misra-Gries is also the basis of the practice problem Top K Frequent Words when the input is too large to count exactly. Its close relative Space-Saving overestimates instead of underestimating, and both summaries can be merged across machines (Mergeable Summaries).
Test yourself
After a Misra-Gries summary with counters has read items, which bound holds for every item ?
- for the top items
Why are there at most decrement steps?
- Because items are removed from the stream
- Because each decrement step makes units of count disappear (the counters and the arriving item), and only units ever arrive
- Because counters are bounded by
- Because the stream is random
The Boyer-Moore majority vote returns candidate x. What do you know?
xoccurs more than times- If any item occurs more than times, it is
x; a second pass is needed to confirm xis the most frequent itemxoccurs at least twice
To find all items with in one pass of Misra-Gries followed by a second, exact pass, how many counters are needed?
- About 10
- 99 (that is, )
- About