Skip to main content

Given a matrix of document vectors and one query vector, return the k documents with the highest cosine similarity. For example, with documents (1, 0), (0, 1) and (1, 1), query (1, 0) and k = 2, return document 0 with score 1.0, then document 2 with score about 0.71.

Coding rounds · Intermediate 2

Short answer

Normalise every document row and the query to length 1, then one matrix-vector product, M @ q, gives all cosine scores. Take the top k with np.argpartition and sort only those k. Cost is O(n d) for the scores plus O(n + k log k) for the selection, instead of O(n log n) for a full sort.

Deeper answer

Clarify the shapes first: documents are n by d, the query has length d, and k may be larger than n, so clamp it with min(k, n). Ask whether the vectors are already normalised, and what to do with an all-zero vector, which would divide by zero.

Cosine similarity is the dot product divided by both lengths. Divide each row by np.linalg.norm(M, axis=1, keepdims=True), with a small floor such as 1e-12 so a zero row scores 0 and not NaN. Do the same for the query. Then sims = M @ q. For the top k, idx = np.argpartition(-sims, k - 1)[:k] finds the k best in linear time, but in no particular order, so sort those k by score afterwards.

Test against a plain loop on random data, test a zero vector, and test k equal to n. Interviewers watch for forgetting that argpartition is unordered, for sorting all n scores when k is small, and for normalising the documents again on every query when their norms could be computed once.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Vector search

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.