Sub topic 3
The Sketch: A Grid of Counters with One Hash Per Row
This chapter assumes you can write basic Python, know how a hash table maps keys to buckets, and understand expected value at the level of "average number of collisions". Earlier chapters explained why exact counting of a large stream can exceed memory, and they refreshed hashing and collisions. Here we build the data structure itself. The next chapter adds the operations that put counts in and read estimates out.
From a hash table to a grid
An exact counter keeps one entry per distinct item, usually in a dictionary. Its memory grows with the number of distinct items. If a stream contains hundreds of millions of distinct search queries, the dictionary grows with them.
A count-min sketch gives up exactness to fix the memory size in advance. It does not store items at all. It stores only counters, and many items share each counter.
The simplest version of this idea is a single array of w counters and one hash function that maps each item to one of the w positions. Two items that map to the same position, which is a collision, share a counter and contaminate each other's counts. A single array has one weakness: if a rare item collides with a very frequent one, nothing tells you the count is wrong.
The count-min sketch repeats the array d times with d different hash functions. A collision that happens in one row is unlikely to happen in every row. The structure is a two-dimensional table:
- It has
drows, called the depth. - It has
wcolumns, called the width. - Every cell is an integer counter that starts at 0.
- Row
jhas its own hash functionh_j, which maps any item to a column number in0..w-1.
The table holds d × w counters no matter how long the stream is or how many distinct items it contains.
What one item maps to
Given an item x, the sketch computes h_0(x), h_1(x), ..., h_{d-1}(x). This gives exactly one cell per row, so each item is associated with d cells in total. Those are the cells the next chapter will increment on an update and read on a query.
The column numbers in the diagram are illustrative. Different rows pick unrelated columns for the same item, and that independence is what makes the structure useful.
How the hash functions are built
Each row needs a function from items to {0, ..., w-1}. Items can be strings, tuples, or anything else, so the sketch works in two steps:
- Convert the item to a large integer
x. - Apply a row-specific function
((a * x + b) mod p) mod w.
Here p is a prime larger than any value of x, and a and b are random numbers chosen once for each row. a is drawn from 1..p-1, and b is drawn from 0..p-1. Because each row draws its own (a, b) pair, the rows behave like different hash functions even though they share one formula. This is a pairwise independent family. A later chapter explains why that property is the one the error analysis needs.
For p we use the Mersenne prime 2^61 − 1, which is greater than any 61-bit integer. Step 1 matters in practice. Python's built-in hash() for strings changes between processes because of hash randomization. A sketch saved to disk, or built on two machines, would then be unreadable. The code below uses hashlib.blake2b, which gives the same integer on every run and every machine.
Implementing the structure
This version takes the width and depth directly. A later chapter shows how to compute them from a target error and failure probability.
import hashlib
import random
P = (1 << 61) - 1 # a Mersenne prime, larger than any 61-bit integer
def to_int(item):
"""Turn any item into a stable integer in [0, P)."""
digest = hashlib.blake2b(str(item).encode("utf-8"), digest_size=8).digest()
return int.from_bytes(digest, "big") % P
class CountMinSketch:
def __init__(self, width, depth, seed=0):
if width < 1 or depth < 1:
raise ValueError("width and depth must be positive")
self.w = width
self.d = depth
rng = random.Random(seed)
# One (a, b) pair per row defines that row's hash function.
self.params = [
(rng.randrange(1, P), rng.randrange(0, P))
for _ in range(depth)
]
# d rows of w counters, all zero.
self.table = [[0] * width for _ in range(depth)]
def columns(self, item):
"""Return the column chosen in each row, one per row."""
x = to_int(item)
return [((a * x + b) % P) % self.w for a, b in self.params]
sketch = CountMinSketch(width=8, depth=3, seed=42)
cols = sketch.columns("apple")
assert len(cols) == sketch.d
assert all(0 <= c < sketch.w for c in cols)
assert cols == sketch.columns("apple") # deterministic for the same item
print("rows:", len(sketch.table), "columns:", len(sketch.table[0]))
print("apple maps to columns", cols)
print("banana maps to columns", sketch.columns("banana"))Running this prints a 3 × 8 table shape and two lists of three column numbers. The exact column numbers depend on the seed and on the hash, but each list always has one entry per row. The assertions encode the two properties the rest of the sketch relies on:
- Every item gets exactly
dcolumn numbers, each within range. - The same item always gets the same columns, so a later read lands on the cells an earlier update touched.
The seed argument makes the hash parameters reproducible. This will matter when we merge sketches, because two sketches can be combined only if their rows use the same hash functions.
Why every row needs its own hash function
It is tempting to use one hash function for all rows, since it saves storage. That defeats the purpose of having rows.
If all rows used the same function, every row would put the same items in the same columns. Two colliding items would collide in every row, and the d rows would hold d identical copies of one array. Adding rows would add memory but no information.
With independent functions, two items that collide in row 0 collide in row 1 only with probability about 1/w. Because the rows are independent, being unlucky in every row at once becomes less likely as d grows. The next chapters turn this intuition into a precise statement.
Memory and cost
The grid is a fixed block of memory, which is the main point of the design.
| Property | Exact dictionary | Count-min sketch |
|---|---|---|
| Memory | Grows with distinct items | `d × w` counters, fixed |
| Stores item identities | Yes | No |
| Counts | Exact | Approximate |
| Work to locate an item | One hash lookup | `d` hash computations |
| Can list known items | Yes | No |
Two consequences follow from the table.
- The sketch cannot tell you which items it has seen. It stores only counters, so you can ask about a specific item but cannot enumerate keys. Finding the most frequent items requires extra bookkeeping, which a later chapter adds.
- Each item costs
dhash evaluations, so time per operation is O(d). The sketch needs onlydmemory accesses per item, anddis typically small.
Counter size also matters in real systems. In Python integers have no fixed size, but in a compact implementation the counters are fixed-width, such as 32-bit integers. They must be large enough to hold the total stream length without overflowing.
Common mistakes
- Using
hash()on strings and sharing the sketch. Values differ between processes, so a sketch built in one run cannot be queried in another. - Picking
was a power of two with weak hash functions. If the hash takes only the low bits of a poor integer, patterns in the input can cluster items. Taking the result modulopbefore reducing byw, as above, avoids this. - Using
a = 0. Thenh(x) = b mod wfor everyx, and all items land in one column. The code drawsafrom1..p-1for this reason. - Creating sketches with different seeds and expecting to combine them. The rows would not line up item by item.
Exercise
A sketch has depth 4 and width 100. (a) How many counters does it hold, and does that number change if the stream grows from one million items to one billion? (b) Suppose someone builds the sketch with the same (a, b) pair in all four rows. How does that change the information the sketch holds?
Show answer
(a) It holds 4 × 100 = 400 counters. The number does not change with stream length or with the number of distinct items, because the table size is fixed at construction. (b) All four rows would map every item to the same column, so the rows would be identical copies of one array. Any two items that collide in one row collide in all rows, and the extra rows would give no additional protection against collisions.
Exercise
Why does the sketch convert items with hashlib.blake2b instead of Python's built-in hash()?
Show answer
Python randomizes hash() for strings per process, so the same string maps to different integers in different runs. A sketch written by one process, or built on another machine, would then use different columns for the same item. blake2b returns the same integer everywhere, so the sketch stays consistent across runs and machines.