InterviewPrepKit

Home / Coding / Agent Coding / Retrieval (RAG) / Top-k Cosine Retriever

Top-k Cosine Retriever

medium 00:00
Solving tips
  • Cosine similarity is a dot product of L2-normalized vectors — normalize once, then it's just matrix-vector multiply.
  • You only need the top k, not a full sort; but a full sort is fine for interview-sized inputs and easier to get right.
  • Guard against zero vectors: a zero-norm document should not blow up with a divide-by-zero.

Build the retrieval half of a RAG pipeline: given a query embedding and a set of pre-computed document embeddings, return the k documents whose embeddings are most similar to the query. This is the “R” in retrieval-augmented generation, and it is a standard warm-up in an agent-coding round.

Cosine similarity

The cosine similarity between two vectors a and b is their dot product divided by the product of their L2 norms:

cos(a, b) = (a . b) / (||a|| * ||b||)

It measures the angle between the vectors and ignores their magnitude, which is why it is the default relevance score for embeddings. If you L2-normalize every vector first, cosine similarity reduces to a plain dot product.

Task

Complete top_k_cosine(query, doc_embeddings, doc_texts, k=3):

  1. Compute the cosine similarity between query and each document embedding.
  2. Pair each score with its document text.
  3. Return the min(k, n) highest-scoring (text, score) tuples, sorted by score descending.

The embeddings are passed in — there is no model call. NumPy is allowed; so is pure Python.

Example

query = [1.0, 0.0]
doc_embeddings = [
    [1.0, 0.0],   # same direction as query  -> cos 1.0
    [0.0, 1.0],   # orthogonal               -> cos 0.0
    [2.0, 0.0],   # same direction, longer   -> cos 1.0
]
doc_texts = ["exact match", "unrelated", "scaled match"]

top_k_cosine(query, doc_embeddings, doc_texts, k=2)
# -> [("exact match", 1.0), ("scaled match", 1.0)]
# (both cosine 1.0; "unrelated" at 0.0 is excluded)

Constraints

  • doc_embeddings and doc_texts have the same length n, and every vector has the same dimension d as query.
  • Handle k larger than n by returning all n documents.
  • A zero vector (norm 0) must not raise; treat its cosine similarity as 0.0.
  • Do not call any embedding model or network — the embeddings are provided.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug