BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Embeddings and RAG19 of 19 in topic

820. Bucket embeddings with random-hyperplane LSH

MediumEmbeddings and RAG Pro

Why it matters Near-duplicate detection and some approximate nearest neighbour indexes use random-hyperplane LSH (SimHash).

Locality-sensitive hashing (LSH) with random hyperplanes gives similar vectors the same bit signature with high probability, so you only compare vectors that share a bucket.

Write lsh_buckets(X, planes). X is (n, d) and planes is (b, d). Bit j of vector x is 1 if planes[j] . x >= 0, else 0. The signature is the integer with bit 0 as the most significant bit (so bits [1, 0, 1] give 5). Return (signatures, buckets) where signatures is a list of ints and buckets is a dict signature -> sorted list of row ids.

Functiondef lsh_buckets(X, planes)

Example 1

Input: lsh_buckets([[1.0, 1.0], [2.0, 0.5], [-1.0, -1.0]], [[1.0, 0.0], [0.0, 1.0], [1.0, -1.0]])

Output: ([7, 7, 1], {7: [0, 1], 1: [2]})

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1

X @ planes.T gives every dot product at once, shape (n, b).

Hint 2

Turn each row of booleans into an integer with bit 0 as the highest bit.

Hint 3

Group row ids by signature with a dict.

Common mistakes
  • Reading bit 0 as the least significant bit.
  • Using > 0 instead of >= 0, which changes vectors that lie on a plane.
Understand the idea

Each random hyperplane splits space in two. Two vectors land on the same side with probability 1 - angle / pi, so vectors with a small angle tend to share most bits. Scaling a vector never changes its signature; negating it flips every bit (except exact zeros).

Worked example

[1, 1] and [2, 0.5] are on the positive side of all three planes, signature 0b111 = 7; [-1, -1] gives [0, 0, 1] = 1 because it lies exactly on the third plane (dot 0 counts as 1).

bit_j = (planes[j] . x >= 0); signature = bits read as binary, bit 0 first
Topics
Embeddings and RAG
Similar questions
  • Split a document into overlapping chunksMedium
  • Combine keyword and vector scores with min-max normalizationMedium
  • Search binary-quantised embeddings by Hamming distanceMedium
  • Chunk text by sentences under a token budgetMedium
All Embeddings and RAG problems
Report
820 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def lsh_buckets(X, planes):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

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