BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Data processing and features43 of 54 in topic

804. Build a Bloom filter for fast near-duplicate checks

MediumData processing and features

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.

Functiondef 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.

Worked example

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
Topics
Data processing and features
Similar questions
  • Split a dataset so every class keeps its shareMedium
  • Bin a feature into quantile buckets learned from training dataMedium
  • Frequency-encode a category with a shared bucket for rare and unseen valuesMedium
  • Generate K-fold train and validation index splitsMedium
All Data processing and features problems
Report
804 / 903
Python 3solution.pyPython idle
1
2
3
4
5
import hashlib
def bloom_check(add_items, query_items, m, k):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS