Bloom Filters
A space-efficient probabilistic data structure that answers membership queries in O(k) time using only a bit array. No false negatives, tunable false positive rate. Used in databases, caches, and networking to avoid expensive lookups.
What is a Bloom filter?
A Bloom filter is a tiny, probabilistic set that answers "definitely not present" or "probably present". It uses a bit array and several hash functions: adding an item sets k bits, and a lookup checks whether all k bits are set. It can give false positives but never false negatives. That makes it a great cheap pre-check before an expensive lookup, such as a database read or a malicious-URL check.
class BloomFilter {
constructor(size = 64) { this.bits = new Uint8Array(size); }
#hashes(s) {
let h1 = 0, h2 = 0;
for (const c of s) { h1 = (h1 * 31 + c.charCodeAt(0)) >>> 0; h2 = (h2 * 17 + c.charCodeAt(0)) >>> 0; }
return [h1, h2, h1 + h2].map((h) => h % this.bits.length);
}
add(s) { this.#hashes(s).forEach((i) => (this.bits[i] = 1)); }
mightContain(s) { return this.#hashes(s).every((i) => this.bits[i]); }
}Bit array — animated
// Array state
// Pseudocode
How it works
What is a Bloom Filter?
A bit array of size m, plus k independent hash functions. Elements are never stored — only their bit signatures. This gives a space savings of 10-100x over a hash set.
Pseudocode
1// Bloom Filter — Insert — O(k)2function insert(filter, item):3 for hashFn in filter.hashFunctions:4 index = hashFn(item) % filter.size5 filter.bitArray[index] = 1 // set bit67// Lookup — O(k)8function contains(filter, item):9 for hashFn in filter.hashFunctions:10 index = hashFn(item) % filter.size11 if filter.bitArray[index] == 0:12 return FALSE // definitely not present13 return MAYBE // could be false positive
Complexity
O(k) time
O(k) time
Constant time
🎯 Quick Check
A Bloom Filter says element X is NOT present. What can you conclude?
Bloom Filters: summary
Key points
- More bits and well-chosen hash counts lower the false-positive rate.
- You can't delete from a standard Bloom filter (a counting Bloom filter can).
- Used by databases (Cassandra, RocksDB), CDNs and browsers.
Frequently asked questions
›Can a Bloom filter give false negatives?
No. If it says "not present", the item was definitely never added. Only "present" answers can be wrong.