Bloom filters and sketches

O(k)·O(m) bits
000000000000000000000000000000000000000000000000000000000000000000448812162024283132 bitsIndex

An empty filter: 32 bits, all zero, and 3 hash functions. Nothing is in it yet, so every query would answer "definitely not present".

An empty filter: 32 bits, all zero, and 3 hash functions. Nothing is in it yet, so every query would answer "definitely not present".
  1. 1start with an array of m bits, all zero
  2. 2to insert an item, set the k bits its k hashes point at
  3. 3to query an item, read those same k bits
  4. 4any zero means definitely absent; all ones means probably present
Bits set
0
Bits read
0

Complexity

BestO(1)
AverageO(k)
WorstO(k)
Extra spaceO(m) bits
bits touched at n=1 predicts 1; this run took 0.

Bloom filter

A Bloom filter is an array of m bits, all zero to begin with, and k independent hash functions. To insert an item you set the k bits its k hashes point at. To ask whether an item is present you read those same k bits: if any one of them is zero the item is definitely not in the set, because inserting it would have set that bit; if all k are one the item is probably in the set, but those bits may have been set by other items between them. The structure never stores the items themselves, which is why it fits in a few bits each.

When it is the right choice

Whenever a cheap, compact "almost certainly not here, do not bother looking" is worth more than an exact answer — a database skipping a disk read for a key that is not in a block, a browser checking a URL against a list of known-bad ones, a cache avoiding a network round trip. The filter is a front door, and whatever it lets through is checked properly behind it.

How it works

Worth noticing

Cost

Best
O(1)
Average
O(k)
Worst
O(k)
Space
O(m) bits

Worth comparing

All probabilistic structures