mediumSystem Design

What is a Bloom filter and when is it useful?

93 views
01

Understand the problem

Explain Bloom filters.

bloom-filter
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Bloom filter (add / contains)
Run Playground
import hashlib

class BloomFilter:
    def __init__(self, size=1000, k=3):
        self.size = size
        self.k = k
        self.bits = [0] * size
    def _positions(self, item):
        for i in range(self.k):
            h = hashlib.md5((str(i) + item).encode()).hexdigest()
            yield int(h, 16) % self.size
    def add(self, item):
        for pos in self._positions(item):
            self.bits[pos] = 1
    def contains(self, item):
        return all(self.bits[pos] for pos in self._positions(item))

bf = BloomFilter()
for name in ["ada", "grace", "linus"]:
    bf.add(name)

print("ada  ->", bf.contains("ada"))    # True  (was added)
print("alan ->", bf.contains("alan"))   # False (definitely not present)
# 'True' can be a false positive; 'False' is always correct.
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.