TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Misra-Gries and the Majority Vote

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 0<ϕ<10 < \phi < 1, the ϕ\phi-heavy hitters of an insertion-only stream of length mm are the items with fx>ϕmf_x > \phi m. There are fewer than 1/ϕ1/\phi of them, so a small output, but finding them exactly in one pass needs Ω(n)\Omega(n) 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 k−1k - 1 counters and estimate every frequency to within m/km/k.

The majority vote: k=2k = 2

The simplest case asks for a majority element, one with fx>m/2f_x > m/2, if there is one. Boyer and Moore (1981) solved it with one candidate and one counter:

text
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 k−1k - 1 counters

Misra-Gries generalizes the cancellation: keep up to k−1k - 1 (item, count) pairs, and when a new item arrives while all k−1k - 1 counters are taken, cancel kk distinct items at once, the newcomer and one copy of each counted item.

text
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 0

With k=2k = 2 it is exactly the majority vote. The animation runs it with k=3k = 3 (two counters) on a stream of 12 items.

The program prints the same trace and compares the final estimates with the true counts.

python · try it yourself
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 f^x\hat f_x be the estimate after an insertion-only stream of length mm, and let m′m' be the sum of the counters at the end. Then for every item xx

fx−m−m′k  ≤  f^x  ≤  fx.f_x - \frac{m - m'}{k} \;\le\; \hat f_x \;\le\; f_x .

In particular f^x≥fx−m/k\hat f_x \ge f_x - m/k, so every item with fx>m/kf_x > m/k has a counter at the end.

Proof. The upper bound is clear: f^x\hat f_x only grows when xx arrives. For the lower bound, call a run of line 6 a decrement step. In a decrement step kk units of count disappear: one from each of the k−1k - 1 counters and the arriving item, which is never counted. All other steps add exactly 1 to the total of the counters. So if dd is the number of decrement steps, m′=m−kdm' = m - kd, that is d=(m−m′)/kd = (m - m')/k. Each occurrence of xx that is not reflected in f^x\hat f_x was lost in a decrement step (either xx's counter was decremented, or xx arrived and was dropped), and each decrement step loses at most one occurrence of xx. Hence fx−f^x≤df_x - \hat f_x \le d. □\square

The trace above shows the bound is tight: there were d=3d = 3 decrement steps, (m−m′)/k=(12−3)/3=3(m - m')/k = (12 - 3)/3 = 3, and both a and b lost exactly 3 occurrences.

Space and time. The summary uses k−1k - 1 items and counters, O(k)O(k) words, independent of mm and nn. A decrement step costs O(k)O(k), but there are at most m/km/k of them, so the amortized time per item is O(1)O(1) plus the dictionary lookup; with a careful structure (counters grouped by value in a linked list) every step is O(1)O(1) in the worst case.

Lower bound. Any one-pass algorithm with additive error less than m/km/k for every item needs Ω(k)\Omega(k) words in the worst case, so Misra-Gries is optimal up to constant factors (a counting argument over streams with kk items of frequency about m/km/k; see Bose, Kranakis, Morin and Tang, 2003, for the precise statement).

Finding the heavy hitters

To report the ϕ\phi-heavy hitters, run Misra-Gries with k=⌈1/ϕ⌉k = \lceil 1/\phi \rceil: every item with fx>ϕm≥m/kf_x > \phi m \ge m/k survives. The survivors may include false positives, which can be removed in two ways:

  • a second pass that counts the at most k−1k - 1 candidates exactly;
  • one pass with a slack: run with k=⌈2/ε⌉k = \lceil 2/\varepsilon \rceil and report items with f^x≥(ϕ−ε/2)m\hat f_x \ge (\phi - \varepsilon/2) m. Every item with fx>ϕmf_x > \phi m is reported and no item with fx<(ϕ−ε)mf_x < (\phi - \varepsilon) m is, which is the usual ε\varepsilon-approximate heavy hitters guarantee.

The program runs Misra-Gries on 100 000 Zipf-distributed items for three values of kk and checks the theorem against exact counts.

python · try it yourself
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 (m−m′)/k(m - m')/k, which is noticeably smaller than m/km/k because the counters still hold part of the stream. Every item above m/km/k was kept. The summary for k=200k = 200 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 jj with probability 34⋅2−(j+1)\frac{3}{4} \cdot 2^{-(j+1)}, mixed with uniform noise over 10510^5 items), with k=20k = 20.

cpp · try it yourself
#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 k−1k - 1 counters has read mm items, which bound holds for every item xx?

  1. fx≤f^x≤fx+m/kf_x \le \hat f_x \le f_x + m/k
  2. fx−m/k≤f^x≤fxf_x - m/k \le \hat f_x \le f_x
  3. f^x=fx\hat f_x = f_x for the top kk items
  4. ∣f^x−fx∣≤m\lvert \hat f_x - f_x \rvert \le \sqrt{m}

Why are there at most m/km/k decrement steps?

  1. Because kk items are removed from the stream
  2. Because each decrement step makes kk units of count disappear (the k−1k - 1 counters and the arriving item), and only mm units ever arrive
  3. Because counters are bounded by kk
  4. Because the stream is random

The Boyer-Moore majority vote returns candidate x. What do you know?

  1. x occurs more than m/2m/2 times
  2. If any item occurs more than m/2m/2 times, it is x; a second pass is needed to confirm
  3. x is the most frequent item
  4. x occurs at least twice

To find all items with fx>m/100f_x > m/100 in one pass of Misra-Gries followed by a second, exact pass, how many counters are needed?

  1. About 10
  2. 99 (that is, k=100k = 100)
  3. About 10410^4
  4. m/100m/100