Sub topic 1
The Problem: Counting Items in a Stream with Limited Memory
Prerequisites
This chapter assumes basic Python, hash functions, hash tables, Big-O notation, and basic probability. You should understand that a hash function maps an item to an integer, usually an array position.
Counting a Stream
Suppose a service receives billions of events and must answer questions such as, “How many times did user A appear?” Exact counting stores one counter for every distinct item. If the item universe is large, a dictionary can consume too much memory.
A count-min sketch trades exactness for bounded memory. It stores a fixed grid of counters. The sketch can overestimate an item's count, but it is designed never to underestimate counts when updates are non-negative.
| Method | Memory | Count result |
|---|---|---|
| Exact dictionary | Grows with distinct items | Exact |
| Count-min sketch | Fixed by error targets | May be too high |
Hashing and Collisions
A hash function maps an item to a bucket. A collision occurs when two different items map to the same bucket. For example, if both apple and banana map to bucket 3, their counts share that bucket.
Collisions cause an item's counter to include contributions from other items. A sketch reduces this error by using several independently behaving hash functions. Each function maps the item to a different row position.
The Sketch: A Grid of Counters
A count-min sketch has d rows and w columns. Each row has its own hash function. To add an item, hash it once per row and increment the selected counter.
To estimate an item's frequency, read one counter from every row and return the minimum. Every selected counter contains the item's updates plus possible collision updates. The minimum is therefore the least contaminated estimate.
class CountMinSketch:
def __init__(self, width, depth):
self.table = [[0] * width for _ in range(depth)]
self.width = width
self.depth = depth
def _column(self, item, row):
return hash((item, row)) % self.width
def add(self, item, count=1):
for row in range(self.depth):
column = self._column(item, row)
self.table[row][column] += count
def estimate(self, item):
return min(
self.table[row][self._column(item, row)]
for row in range(self.depth)
)
sketch = CountMinSketch(width=10, depth=3)
for _ in range(4):
sketch.add("apple")
print(sketch.estimate("apple")) # 4 or greaterExercise
Why does a count-min sketch return the minimum of its row counters instead of the maximum?
Show answer
Each counter can include collision noise, so the minimum is the least inflated estimate.