KatInterview

Top-K Document Retrieval by Cosine Similarity

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingvectorssimilarityranking

Last updated

Tests vector similarity computation, efficient top-k selection with deterministic tie-breaking, and understanding of distance metrics in embedding spaces.

You are building a document retrieval system that finds the most relevant documents for a given query based on their vector embeddings.

Write a function that takes a collection of document vectors, a query vector, and an integer k, then returns the k documents most similar to the query according to cosine similarity.

Cosine similarity between two vectors u and v is defined as:

cos_sim(u, v) = (u · v) / (||u|| × ||v||)

where u · v is the dot product and ||u|| is the Euclidean norm (L2 norm).

Input

  • doc_vectors: A list of document vectors, where each vector is a list of floats
  • query_vector: A single query vector as a list of floats
  • k: The number of top results to return

Output

Return a list of tuples, where each tuple contains:

  1. The document index (its position in the input list)
  2. The document vector itself
  3. The cosine similarity score

The results must be ordered by:

  • Primary: Descending cosine similarity (highest first)
  • Tie-breaker: Ascending document index (lower index first)

Return at most k results. If there are fewer than k documents, return all of them.

Edge Cases

  • If either the query vector or a document vector has zero magnitude (all zeros or empty), treat the cosine similarity as 0.0
  • If k is zero or negative, return an empty list
  • All vectors in the input have the same dimensionality

Constraints

  • 0 ≤ number of documents ≤ 10,000
  • 0 ≤ k ≤ number of documents
  • 1 ≤ vector dimension ≤ 1,000
  • All vector elements are finite floats

Examples

Example 1

Input: top_k_cosine_documents([[1, 0], [0, 1], [-1, 0]], [1, 0], 2)

Output: [[0, [1, 0], 1], [1, [0, 1], 0]]

Example 2

Input: top_k_cosine_documents([[1, 1], [2, 2], [1, 0]], [1, 1], 3)

Output: [[0, [1, 1], 0.9999999999999998], [1, [2, 2], 0.9999999999999998], [2, [1, 0], 0.7071067811865475]]

Hints

Hint 1

Cosine similarity measures the angle between vectors, not their magnitude—consider normalizing vectors first.

Hint 2

For tie-breaking, when two documents have identical scores, the one with the smaller index should appear first in the output.

Hint 3

Handle the zero-vector case explicitly to avoid division by zero when computing norms.