Explaining count-min sketch
A Count-Min Sketch approximates frequency counts using a 2D array with d rows and w = O(1/ε) columns, each row having a distinct hash function. Updates increment counters at hashed positions, and queries return the minimum of these counters, which always overestimates true frequencies due to potential collisions incrementing counters for other elements. Its memory is O(d×w) = O((1/ε) log(1/δ)), guaranteeing with probability 1-δ that the error is within ε times the total count, providing an additive error bound with fast, space-efficient approximate counting.
A Count–Min Sketch (CMS) is a probabilistic data structure used to approximate frequencies of items in a stream. It is especially useful when memory is limited and exact counting is not feasible.
How It Works
-
Structure:
- A CMS uses a 2D array (often called a “table”) with (d) rows and (w) columns.
- Each of the (d) rows has its own hash function (h_i), which maps any item to one of the (w) columns in that row.
-
Update:
- When an item (x) appears, you compute (h_i(x)) for each row (i) and increment the counter in row (i), column (h_i(x)).
-
Query:
- To estimate the frequency of item (x), you compute (h_i(x)) for each row and look up the corresponding counters. The estimated count is the minimum of those (d) counters:
[
\hat{f}(x) = \min_{i=1..d} \text{table}[i][h_i(x)].
]
Why the Query Result Is Always an Over-Estimate
- Each counter may be incremented not only by item (x) but also by other items that hash to the same position. These “collisions” add extra counts to that counter.
- Because counters are only incremented, never decremented, the estimated frequency of (x) can be larger than (or equal to) the true frequency. Taking the minimum across multiple rows helps reduce—but not eliminate—the over-estimate, since it is unlikely that all rows suffer from the same large collision for (x).
Space Complexity vs. Error Bound
-
Let:
- ( \varepsilon ) be the allowable error in the count estimate (as an additive error proportional to the total number of items processed).
- ( \delta ) be the probability that the error bound is violated.
-
With width ( w = \left\lceil \frac{e}{\varepsilon} \right\rceil ) and depth ( d = \lceil \ln(\frac{1}{\delta}) \rceil ), the CMS guarantees:
[
\hat{f}(x) \leq f(x) + \varepsilon \cdot N
]
with probability at least ( 1 - \delta ), where:
- ( f(x) ) is the true frequency of item (x),
- ( N ) is the total number of items processed.
-
Space usage is ( O(d \times w) ), which translates to:
[
O!\Bigl(\tfrac{1}{\varepsilon} \cdot \ln(\tfrac{1}{\delta})\Bigr).
]
This means you can control the accuracy (via (\varepsilon)) and confidence (via (\delta)) by adjusting the size of the CMS.