Top-K Document Retrieval by Cosine Similarity
Arrays & HashingAuto-graded · 18 test casesLast 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 floatsquery_vector: A single query vector as a list of floatsk: The number of top results to return
Output
Return a list of tuples, where each tuple contains:
- The document index (its position in the input list)
- The document vector itself
- 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
kis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core task is to compute cosine similarity between the query and each document, then select the top k results with proper tie-breaking.
Algorithm:
- Compute query norm once: Calculate the L2 norm (square root of sum of squares) of the query vector upfront to avoid redundant computation
- Score each document: For each document, compute its norm, then calculate the dot product with the query, and divide by the product of norms to get cosine similarity
- Handle zero vectors: If either vector has zero magnitude, assign a similarity of 0.0 to avoid division by zero
- Sort with tie-breaking: Sort all scored documents by descending similarity, using document index as a secondary ascending key for deterministic tie resolution
- Return top k: Slice the sorted list to return at most k results
Why this works:
Cosine similarity measures the cosine of the angle between two vectors, ranging from -1 (opposite) to 1 (identical direction). It is scale-invariant—multiplying a vector by a positive constant does not change its cosine with other vectors. The formula (u · v) / (||u|| × ||v||) directly computes this from the geometric definition.
By sorting with (-score, index) as the key, we ensure that higher scores come first, and among equal scores, lower indices come first, producing deterministic output.
Relationship to other metrics:
- Dot product: When both vectors are unit-normalized (norm = 1), dot product equals cosine similarity. Without normalization, dot product conflates magnitude and direction.
- Euclidean distance: For unit-normalized vectors,
||u - v||² = 2(1 - cos_sim(u, v)), so minimizing Euclidean distance is equivalent to maximizing cosine similarity. For unnormalized vectors, Euclidean distance is dominated by magnitude differences.
Complexity:
- Time: O(n × d + n log n) where n is the number of documents and d is the vector dimension. We spend O(d) per document computing dot product and norms, then O(n log n) sorting.
- Space: O(n) to store the scored list
Reference Solution
import math
from typing import List, Tuple
def top_k_cosine_documents(doc_vectors: List[List[float]], query_vector: List[float], k: int) -> List[Tuple[int, List[float], float]]:
if k <= 0:
return []
query_norm = math.sqrt(sum(x * x for x in query_vector))
scored = []
for i, doc in enumerate(doc_vectors):
doc_norm = math.sqrt(sum(x * x for x in doc))
if query_norm == 0.0 or doc_norm == 0.0:
score = 0.0
else:
dot = sum(a * b for a, b in zip(doc, query_vector))
score = dot / (doc_norm * query_norm)
scored.append((i, doc, score))
scored.sort(key=lambda item: (-item[2], item[0]))
return scored[:k]