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 with m bits and k hash functions
  • add(item) - Add an item to the filter
  • contains(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
Bloom Filter ImplementationINPUTOperations:["BloomFilter",10,3]["add","apple"]["contains","apple"]["contains","banana"]m=10 bits, k=3 hashesALGORITHM STEPS1Initialize bit array[10] = 02Hash "apple" to positions 1,3,63Set bits[1]=bits[3]=bits[6]=14Check membership by testing bitsBit Array After Adding "apple":[0,1,0,1,0,0,1,0,0,0]positions: 0 1 2 3 4 5 6 7 8 9FINAL RESULTOperation Results:null (constructor)null (add operation)true (apple found)false (banana not added)Output Array:[null,null,true,false]Key Insight:Bloom filters use multiple hash functions to map items to bit positions, enabling space-efficientmembership testing with possible false positives but guaranteed no false negatives.TutorialsPoint - Bloom Filter Implementation | Probabilistic Data Structure
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen