SDE & MLE Prep

Probabilistic Data Structures

Trade a small, bounded error for huge memory savings — ideal for "have we seen it?", "how many?", "how often?" at scale.

StructureAnswersErrorSize
Bloom filter"is x in the set?"false positives only (never false negatives)~9.6 bits per element for 1% false positives
Count-Min Sketch"how often did x occur?"overestimates onlyd × w counters, independent of the number of items
HyperLogLog"how many distinct items?"~1.04/√m relative standard errorRedis: 12 KB → 0.81% error for billions of items
Bloom filter (m bits, k hash functions):   add x  -> set bits h1(x) .. hk(x)
                                           query  -> all k bits set ? "maybe" : "definitely not"
false-positive rate ≈ (1 − e^(−kn/m))^k,   best k = (m/n)·ln 2
  • Bloom: skip disk reads for absent keys (LSM SSTables in Cassandra/Bigtable/RocksDB), "already crawled this URL?", "username probably taken?". No deletes (use a counting Bloom filter or a cuckoo filter).
  • Count-Min: d hash rows of w counters; an update increments one counter per row; the estimate is the minimum over the rows. Trending / heavy hitters = CMS + a min-heap of the current top k.
  • HyperLogLog: hash each item, keep per bucket the longest run of leading zeros seen, combine buckets with a harmonic mean. Daily active users, unique visitors; sketches are mergeable (union across shards or days for free).