progress

~/problems / Arrays & hashing / Hash maps and counting

Bloom Filter

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

The Name Guard can't remember a billion names, so it keeps m lamps. Registering a name lights the k lamps its hashes point at. For a query, any dark lamp means definitely not taken; all lit means it might be (a false alarm is possible).

Build BloomFilter(m, k) (m bits, all 0) with add(word) (set the word's k bits) and might_contain(word) (True if all k bits are set). The hashes are fixed (code(c) is the ASCII code):

P = 998244353
h1(word):  h = 0, then for each letter c from left to right:  h = (h * 65537 + code(c)) mod P
h2(word):  h = 0, then for each letter c from left to right:  h = (h * 12345 + code(c)) mod P
position i, for i = 0, 1, ..., k - 1:   (h1 + i * h2) mod m
g = BloomFilter(16, 3)
g.add("ana")               # h1 = 363855759, h2 = 808642530: bits 15, 1, 3
g.add("bob")               # bits 14, 11, 8
g.add("cyd")               # bits 7, 0, 9
g.might_contain("bob")     # True
g.might_contain("dan")     # False   its bits are 5, 1, 13: bit 5 is dark
g.might_contain("eve")     # True    bits 14, 15, 0 were lit by bob, ana and cyd

The tests expect false alarms like "eve", so a set of words won't work.

  • 1 <= m <= 10^6, 1 <= k <= 10; words are 1 to 20 lowercase letters. In C++/Java use 64-bit arithmetic.
  • ⭐ Bonus: a speed test earns a star at O(length + k) per call.
Show hint

compute h1 and h2 once per word; a list of m booleans is all the storage you need.

Topic: Hash maps and counting. Counter/defaultdict, complement lookups, prefix-sum + hash map.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc