Suryanand/ Bootcamp
suryanand.com ↗Let's talk
Frame · dsa / ai-algorithms / 09-minhash-lsh-near-duplicates.jsJavaScript

MinHash and Locality-Sensitive Hashing for Near-Duplicate Detection

Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.

Same file as in the repo · ~20s timeout

From file header (JSDoc)

MinHash and Locality-Sensitive Hashing for Near-Duplicate Detection

Problem: Training-data and RAG pipelines must drop near-duplicate
documents without comparing every pair. Implement:
- `shingles(text, n)`: the set of lowercase word n-grams of a document.
- `minhashSignature(set, numHashes, seed)`: for each of `numHashes` seeded
  32-bit hash functions, the minimum hash over the set. The probability two
  signatures agree at a position equals the Jaccard similarity of the sets.
- `estimateJaccard(sigA, sigB)`: the fraction of equal positions.
- `lshCandidates(signatures, bands)`: split each signature into `bands`
  bands of r = numHashes / bands rows; documents that share an identical
  band in the same band position become candidate pairs. Return the sorted
  list of unique pairs `[i, j]` with i < j.

Constraints:
- numHashes divisible by bands; documents up to 10^6

Example:
  docs = ["the quick brown fox ... river bank today",
          "the quick brown fox ... river bank tonight",
          "stock prices fell sharply in early trading ..."]
  2-word shingles, 128 hashes, 32 bands
  -> lshCandidates(...) contains [0, 1] and not [0, 2]

Approach: Hash each shingle once with FNV-1a, then derive numHashes
functions by XOR-ing with seeded constants and applying a murmur3 finaliser.
Signatures cost O(|set| * numHashes). LSH buckets each band (key = band
index + row values), so similar pairs collide with probability
1 - (1 - s^r)^bands. Time O(N * numHashes) plus bucket pairs, space
O(N * numHashes).
@param {string} text
@param {number} n
@returns {Set<string>}
Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.