Suryanand/ Bootcamp
suryanand.com ↗Let's talk
Frame · dsa / ai-algorithms / 01-cosine-similarity-top-k-neighbours.jsJavaScript

Cosine Similarity and Top-K Nearest Neighbours

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)

Cosine Similarity and Top-K Nearest Neighbours

Problem: Given a query embedding and a list of document embeddings
(`{ id, vector }`), return the `k` documents most similar to the query by
cosine similarity, sorted from most to least similar. Ties are broken by
the lower original index. A zero vector has similarity 0 with everything.

Constraints:
- 1 <= vectors.length <= 10^5, all vectors share the same dimension d
- 1 <= k; if k > n, return all n documents

Example:
  query = [1, 0], docs = [{a,[1,0]}, {b,[0,1]}, {c,[1,1]}], k = 2
  -> [{ id: "a", score: 1 }, { id: "c", score: 0.7071... }]

Approach: Cosine similarity is dot(a, b) / (|a| * |b|). Instead of sorting
all n scores, keep a min-heap of size k whose root is the weakest of the
current best k; a new score only enters if it beats the root. Finally sort
the k survivors. Time O(n*d + n log k), space O(k).
@param {number[]} query
@param {{ id: string, vector: number[] }[]} docs
@param {number} k
@returns {{ id: string, score: number }[]}
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.