Bloom Filter - Problem
A Bloom filter is a space-efficient probabilistic data structure designed to test whether an element is a member of a set. It can return false positives but never false negatives - if it says an element is not in the set, it's definitely not there.
Implement a Bloom filter with the following operations:
BloomFilter(m, k)- Initialize withmbits andkhash functionsadd(item)- Add an item to the filtercontains(item)- Check if item might be in the set (may return false positives)
For this implementation, use simple hash functions: hash_i(x) = (hash(x) + i * hash2(x)) % m where hash(x) = sum of ASCII values and hash2(x) = product of ASCII values % 997.
Input & Output
Example 1 — Basic Bloom Filter Operations
$
Input:
operations = [["BloomFilter",10,3],["add","apple"],["contains","apple"],["contains","banana"]]
›
Output:
[null,null,true,false]
💡 Note:
Create filter with 10 bits and 3 hash functions, add 'apple', check 'apple' (true), check 'banana' (false since not added)
Example 2 — Multiple Items
$
Input:
operations = [["BloomFilter",8,2],["add","cat"],["add","dog"],["contains","cat"],["contains","bird"]]
›
Output:
[null,null,null,true,false]
💡 Note:
Add 'cat' and 'dog', then check 'cat' (true) and 'bird' (false - not added)
Example 3 — Potential False Positive
$
Input:
operations = [["BloomFilter",5,2],["add","a"],["contains","b"]]
›
Output:
[null,null,false]
💡 Note:
Small filter size increases collision chance, but 'b' hashes to different positions than 'a'
Constraints
- 1 ≤ m ≤ 104
- 1 ≤ k ≤ 10
- 1 ≤ operations.length ≤ 1000
- All strings contain only lowercase English letters
- 1 ≤ string.length ≤ 20
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code