Bloom Filter
A bit array and k hash functions that answer is this item in the set with a certain no or a probable yes, in a fraction of the memory a real set needs.
Overview
A Bloom filter is a set that can say no with certainty and yes only with high probability. It stores no items, only a bit array of m bits, all 0 at the start. To add an item you hash it k ways and set those k bits to 1. To test an item you hash it the same k ways: if any of the bits is still 0, the item was never added; if all are 1, it was probably added, but other items may have set those bits between them.
Burton Bloom published the idea in 1970 to keep a hyphenation dictionary in memory when the whole dictionary would not fit. That is still the job: stand in front of something expensive (a disk read, a network call, a database query) and answer most of the misses without touching it. The price is a false positive rate you choose when you size the filter, and the fact that a plain filter cannot delete.
So the filter gives two answers, and they are not equally strong.
- No: the item is not in the set, always. Skip the expensive lookup.
- Yes: the item is probably in the set, and the answer is wrong with probability about p. Do the lookup; it occasionally finds nothing.
The structure
The class is small because the state is small. It keeps m, k and the bit array, and it works out an item's k positions again on every call instead of storing them.
Interview questions
- Size a Bloom filter for a million items at 1% false positives, and say what happens if two million arrive.
- Why can a Bloom filter not delete, and how does a counting filter fix it?
- Where do Bloom filters sit in real systems?
- Bloom filter, hash set or cuckoo filter: how do you choose?
- Where do the k hash functions come from?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio