Bloom filter
Фильтр Блума
A compact data structure that checks whether an item was added to a set. It can rule an item out with certainty, but it can only say that an item might be present.
What problem does it solve?
Suppose a storage engine gets a lookup for a key that does not exist. Reading disk files just to find that out can be expensive. A Bloom filter is a small structure the engine can check first. A negative result lets it skip the lookup; a positive result means it still has to check the actual data. The filter saves memory by storing a pattern of bits rather than the keys themselves.
How it works
Start with an array of m zero bits. For each key, compute k hash values and map them to positions in the array, for example by taking each value modulo m.
- Insert: set the bit at each of the key's positions to
1. - Query: compute the same positions. If any bit is
0, the key was not inserted. If every bit is1, report “possibly present.”
An absent key can get a positive result if other keys have already set all of its positions. That's a false positive. An inserted key cannot get a negative result as long as its bits aren't cleared and the query uses the same hashing rules. Inserts and queries take up to k hash computations and bit accesses, or O(k) time if each hash computation is treated as constant time. The bit array uses m bits.
A small example
Say tea sets positions 2 and 5, and coffee sets positions 4 and 7. If juice maps to positions 2 and 7, the filter says “possibly present” even though nobody inserted it. If water maps to positions 2 and 6, the filter rules it out because bit 6 is still zero. The positive result for juice tells you to check the source of truth, not to return a record.
Where it fits and where it doesn't
An LSM-tree storage engine such as RocksDB can use a Bloom filter to skip files that cannot contain the requested key. This pays off when misses are common and the work avoided costs more than checking the filter. As more keys are inserted into a fixed-size filter, more bits become set, and queries for absent keys are more likely to return positive.
A standard Bloom filter does not support deletion: clearing an item's bits can make another inserted item look absent. A counting Bloom filter replaces bits with counters so that a valid removal can decrement them, at the cost of more memory. You still need to know that the item was inserted before removing it.
What interviewers ask
Be ready to explain when you'd choose a Bloom filter over a hash set. A hash set stores keys and gives exact membership answers; a Bloom filter is useful when a compact precheck can avoid expensive work and positives can be verified. For a design question, start with the expected number of distinct keys and the tolerated false-positive rate. Use those to size the bit array and choose the number of hashes. More hashes are not automatically better: they cost CPU time and set more bits per insertion.