How often has each item appeared in a stream of billions? Storing an exact counter per distinct item can blow your memory. The Count–Min Sketch answers approximately in a fixed grid: d rows of w counters. Each item bumps one counter per row (chosen by d hashes), and you estimate its count by taking the minimum across its d cells. Collisions can only inflate a cell, so the min can over-count — but it can never under-count. Feed the stream and query.
d rows × w counters. Fixed size, no matter how many distinct items.
d hashes
One hash per row maps an item to one counter in that row.
update
On each event, increment the item’s one counter in every row.
estimate
The minimum of the item’s d counters — collisions inflate, min limits the damage.
cms.js — d rows, w counters, take the min
Ready
A grid of d=3 rows × w=8 counters, all zero. Each event bumps one counter per row (chosen by that row’s hash). Add event to feed the stream; Query to estimate a count.
0
events
–
true count
–
estimate (min)
How it works
The estimate is a minimum, and that choice is the whole design. Every one of an item’s d counters holds its true count plus whatever other items happened to hash to the same cell — so every counter is an over-estimate. Taking the smallest of the d counters keeps the one least polluted by collisions. It’s still ≥ the true count (over-count possible), but it can never drop below it (no under-count), because the item’s own increments are in every one of those cells.
1
Update: bump one cell per row
On each event for item x, use row 0’s hash to pick a column and increment it; same for row 1, row 2. x contributes to exactly d cells.
2
Cells collect collisions
Other items may hash to the same cells and bump them too. So each of x’s counters holds x’s count plus some noise — always an over-estimate, never an under-estimate.
3
Estimate: take the minimum
Read x’s d counters and return the smallest. That’s the counter least inflated by other items — the tightest available upper bound on x’s true count.
✓
Tune the error
More columns w shrinks collisions (tighter estimates); more rows d shrinks the chance all d cells are unlucky. Together they bound the over-count with high probability — in fixed space, independent of stream length.
Update / query
O(d)
Space
d × w counters
Under-count
Never
Over-count
Bounded
The code
# d rows, w counters each. Fixed space, one hash per row.class CountMinSketch:
def __init__(self, d, w):
self.w = w
self.grid = [[0]*w for _ in range(d)]
def add(self, x, c=1):
for r, row in enumerate(self.grid):
row[hash_r(x, r) % self.w] += c # bump one cell per rowdef estimate(self, x):
return min(row[hash_r(x, r) % self.w] # the least-polluted cellfor r, row in enumerate(self.grid))
Quick check
1. Why does the Count–Min Sketch take the minimum across rows?
Each of the item’s d counters holds its true count plus collision noise, so each is ≥ the truth. The minimum picks the counter least polluted by other items — still an over-estimate, but the tightest one available.
2. Can a Count–Min Sketch ever return LESS than the true count?
Never. Each event increments all d of the item’s cells, so every one of them is at least the true count. Collisions can only add extra, so the minimum is ≥ truth — over-counts possible, under-counts impossible.
3. What grows the space of a Count–Min Sketch as the stream gets longer?
The grid is a fixed d×w chosen up front. It uses the same memory whether the stream has a thousand or a trillion events — that fixed footprint is the whole point.
FAQ
What is a Count–Min Sketch?
A probabilistic structure that estimates item frequencies in a stream using a fixed grid of d rows × w counters and d hashes. Each event bumps one counter per row; the estimate is the minimum of an item’s d counters. It over-counts but never under-counts.
How is it different from a Bloom filter?
A Bloom filter answers membership (is x present?) with bits; a Count–Min Sketch answers frequency (how often is x?) with counters. Both use several hashes and have one-sided error — a Bloom filter never false-negatives, a sketch never under-counts.
Where is the Count–Min Sketch used?
Streaming analytics and network monitoring: finding heavy hitters, tracking trending topics or IPs, anomaly detection, and query optimizers estimating value frequencies — anywhere you need per-item counts over a huge stream in bounded memory.
How do you choose d and w?
They set the error bound: columns w control the additive error (≈ e/w × total count), rows d control the confidence it stays within bound (failure prob ≈ e⁻ᵈ). Pick w for tightness, d for confidence — trading memory for accuracy.
The picture: one grid, three lookups
A 3 × 8 grid after the stream apple ×6, banana ×3, cherry ×2, then date, elder, fig and grape once each. The highlighted cells are where date hashes. Red marks a cell polluted by other items; green is a cell holding exactly the true count. The smallest of the three is the answer.
Worked example, step by step
Take d = 3 rows, w = 8 columns and a stream of 15 events: apple ×6, banana ×3, cherry ×2, and date, elder, fig, grape once each. The hash for row r is FNV-1a over the item's characters, seeded with r + 1, finished with the murmur3 mixing steps, then taken mod 8. Every number below comes from running that code. The table is read after all 15 events are in.
Item
True
Columns (r0, r1, r2)
Counters read
Estimate
Error
apple
6
5, 4, 0
6, 10, 7
6
0
banana
3
6, 4, 1
5, 10, 3
3
0
cherry
2
2, 5, 2
2, 2, 4
2
0
date
1
6, 4, 0
5, 10, 7
5
+4
elder
1
6, 6, 2
5, 1, 4
1
0
fig
1
3, 1, 5
2, 1, 1
1
0
grape
1
3, 0, 2
2, 1, 4
1
0
1 of 7 items come back too high (date by 4), and none comes back too low. Look at date: its counters are 5, 10, 7. All 3 cells were shared with other items, so even the minimum is 4 too high. That is the failure case of the structure: an item is only wrong when every one of its 3 cells is shared, and with 8 columns for 7 items that is easy to hit. The other six items each had a cell holding exactly its own count and came back exact. The complexity section measures the same thing at a realistic size.
Complexity and trade-offs
Case
Time
Space
Why
Count-Min Sketch
O(d) per update and query
O(d · w), fixed
Never under-counts. Error is additive, about e/w times the total count, with failure probability about e−d.
Hash map of counters
O(1) expected
O(distinct items)
Exact, but memory grows with every new key, including every one-off key in a stream.
Sort and count
O(n log n)
O(n)
Exact, offline only. Needs the whole stream stored.
Count Sketch (signed counters)
O(d)
O(d · w)
Unbiased estimate that can be low or high; Count-Min trades that for a one-sided guarantee.
Bloom filter
O(k)
O(m) bits
Answers "seen?" not "how many?". Same family, one bit per cell instead of a counter.
The guarantee is in terms of the total count, not the item's count. On the page's own stream (apple ×100, banana ×5, 500 one-off items, 605 events) with w = 256 and d = 4, the bound is e/256 × 605 = 6.42. Measured over all 502 items: the largest error was 3, the mean error 0.69, 279 items were over at all, and 0 exceeded the bound (the textbook ceiling is about e−4 = 1.83% of queries). Apple came back 101 for a truth of 100 (+1); banana 5 for 5 (+0). The error is tiny against a heavy hitter and large against a rare item, which is why the sketch finds the top of a stream well and the bottom of it badly.
Common mistakes
Using one hash function for every row
If all 3 rows use the same hash, they collide on the same items and the minimum has nothing to choose between. On the 15-event stream with the row-1 hash in all three rows, elder (true 1) reads 5 instead of 1 in the proper sketch, because every row is polluted identically. Each row needs its own seed.
Adding the rows instead of taking the minimum
Summing the counters triples the noise. For date the three cells are 5 + 10 + 7 = 22, against a true count of 1. The minimum is 5.
Making w too small
One row of 16 columns holding the 502 items above gives banana an estimate of 33 for a true 5, because about 31 items share every cell. Error scales as total / w; size w from the stream length, not from the number of distinct keys you expect.
Trusting estimates of rare items
The error is additive and the same for every item, so a count of 1 can read as 5 in the grid above. Use the sketch for heavy hitters and thresholds, not to rank the long tail.
Deleting with negative counts
Decrementing is only safe if you decrement exactly what you added, once per event. Subtracting for an item that never arrived pushes shared cells below other items' true counts, and the "never under-counts" guarantee is gone.
Where this shows up
Heavy hitters in a stream
Pair the sketch with a small heap of the current top candidates. Each arriving item updates the sketch, reads its estimate, and enters the heap if it ranks. Memory stays fixed however many distinct keys pass through.
Network and abuse monitoring
Counting packets, requests or login attempts per source address, where the number of sources is unbounded and an over-count only makes an alert fire slightly early.
Query planning
A database that wants to know roughly how often a value occurs in a column can keep a sketch per column instead of a full histogram of distinct values.
Merging across machines
Two sketches built with the same d, w and hashes combine by adding the grids cell by cell. Each worker sketches its shard and a coordinator merges, with no raw data moved.
SOLVE IT YOURSELF
Solve it: count a billion items in a kilobyte
A hash map of counters is exact and enormous. A Count-Min sketch is a fixed grid that never undercounts — it only ever guesses high, and you get to choose how high. Python or TypeScript.
YOUR TASK
Implement build_sketch(items, w, d) — a d × w grid where each item increments one cell per row — and estimate(table, item), which returns the minimum across those cells.
HINTS — 6 IDEAS
Each of the d rows has its own hash. Adding an item increments exactly one cell in every row.
To estimate, read the same d cells and take the minimum.
Why the minimum: every cell holds the item’s true count plus collisions from other items. Collisions only ever add, so every cell is an over-estimate — and the smallest is the tightest one.
This gives a strict one-sided guarantee: estimate >= true count, always. There are no false negatives, only inflated counts.
Taking the minimum across rows is what makes error unlikely: to be badly wrong, an item must collide with something heavy in every row at once.
Widen w to shrink the error, deepen d to shrink the probability of a bad estimate — the tests check both directions.