Misra-Gries Heavy Hitters

Find items with frequency > n/k using only k−1 counters — watch the decrement-all step

Space O(k) Per item O(1) amortized Pass 1 (one pass) Error undercount ≤ n/k
Slow Fast

Stream (processed one item at a time)

Counter slots (k−1 = 2)

increment
claim free slot
decrement-all / drop
Processed
0
n (total)
0
Threshold n/k
0
Decrement-all events
0
Max events (n/k)
0
Step
0/0

What's happening

Press Run to start, or Step to advance one item at a time.

Complexity

OperationCostNote
Process one item (avg)O(1)hash lookup + increment/claim
Decrement-all (worst per item)O(k)touches all k−1 counters; ≤ n/k times total
Whole passO(n)amortized over the stream
SpaceO(k)fixed, independent of distinct count
Naive exact countingO(distinct)full hash map — blows up memory

Operation log