← All Exercises

Bloom Filter with Double Hashing

intermediatejavascript~25min

Background

Bloom filters answer set membership in constant memory with a bounded false-positive rate and no false negatives. They back cache lookups, word validators in browsers, and anti-spam checks.

Problem

Implement a bloom filter over m bits using k hash functions derived from double hashing: h1 is FNV-1a of the string, h2 is FNV-1a of the reversed string (or 1 when zero), and position i is (h1 + i * h2) mod m. Insert all items, then answer membership for every check string.

Input

A JSON object {"bits": number, "hashes": number, "items": string[], "checks": string[]}.

Output

A JSON object {"bitset": string, "membership": boolean[]} with one bit character per position and one answer per check.

Sample tests

Sample 1

Input: {"bits":8,"hashes":2,"items":["a"],"checks":["a","e","b"]}
Expected: {"bitset":"10001000","membership":[true,true,false]}

Sample 2

Input: {"bits":32,"hashes":3,"items":["alpha"],"checks":["alpha","beta"]}
Expected: {"bitset":"01000000000100000000001000000000","membership":[true,false]}

Your solution

Learning objective

Practice bit-level data structures, double hashing derivation, and reasoning about probabilistic membership.