804. Build a Bloom filter for fast near-duplicate checks
Why it matters Dataset dedup pipelines for LLM pretraining and web crawlers use Bloom filters to skip already-seen URLs and documents.
Deduplicating a web-scale training set needs a memory-light way to ask "have I seen this before?". A Bloom filter answers with no false negatives and a small, tunable false positive rate.
Write bloom_check(add_items, query_items, m, k). Use a bit array of m bits, all 0. The i-th hash (i = 0..k-1) of a string s is int(hashlib.md5(f"{i}:{s}".encode()).hexdigest(), 16) % m. Adding s sets those k bits to 1. A query returns True if all k bits are 1.
Return (answers, bits_set) where answers is a list of bools for query_items and bits_set is the number of 1 bits after all adds.
def bloom_check(add_items, query_items, m, k)Example 1
Input: bloom_check(['cat', 'dog'], ['cat', 'cow'], 64, 3)
Output: ([True, False], 6)
Example 2
Input: add_items = [], query_items = ['a'], m = 8, k = 2
Output: ([False], 0)
Example 3
Input: bloom_check(['a', 'a', 'a'], ['a'], 16, 2)[1] <= 2
Output: True
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Write one helper that returns the k bit positions for a string.
Hint 2
Adding the same item twice sets the same bits, so bits_set does not grow.
Common mistakes
- Using Python's built-in hash(), which changes between runs.
- Clearing bits on delete, which breaks other items (plain Bloom filters cannot delete).
Understand the idea
k hash functions each pick one bit. An added item sets its k bits; a query checks them. Every added item answers True, so there are no false negatives. Other items answer True only if all their bits were set by chance.
with nothing added, every bit is 0, so any query is False and bits_set is 0.
add sets bits h_i(s) % m; query = all those bits are 1