PIXELBANKv9.1.0
Menu

Implement top-K retrieval using cosine similarity.

Given a query vector and a set of document vectors, find the K most similar documents.

Input:

  • Line 1: N D K (num documents, dimension, K)
  • Line 2: query vector (D floats)
  • Next N lines: document vectors (D floats each)

Output: Indices of top-K documents (0-based), sorted by similarity descending. Break ties by lower index first.

Example:

Input:
3 2 2
1.0 0.0
1.0 0.0
0.0 1.0
0.5 0.5
Output:
0 2
Reasoning:
  • The query vector is (1.0,0.0)(1.0, 0.0) and the document vectors are (1.0,0.0)(1.0, 0.0), (0.0,1.0)(0.0, 1.0), and (0.5,0.5)(0.5, 0.5).
  • We calculate the cosine similarity between the query vector and each document vector:
    • sim0=(1.0,0.0)â‹…(1.0,0.0)∥(1.0,0.0)∥⋅∥(1.0,0.0)∥=1.0sim_0 = \frac{(1.0, 0.0) \cdot (1.0, 0.0)}{\|(1.0, 0.0)\| \cdot \|(1.0, 0.0)\|} = 1.0,
    • sim1=(1.0,0.0)â‹…(0.0,1.0)∥(1.0,0.0)∥⋅∥(0.0,1.0)∥=0.0sim_1 = \frac{(1.0, 0.0) \cdot (0.0, 1.0)}{\|(1.0, 0.0)\| \cdot \|(0.0, 1.0)\|} = 0.0,
    • sim2=(1.0,0.0)â‹…(0.5,0.5)∥(1.0,0.0)∥⋅∥(0.5,0.5)∥=0.50.5=22sim_2 = \frac{(1.0, 0.0) \cdot (0.5, 0.5)}{\|(1.0, 0.0)\| \cdot \|(0.5, 0.5)\|} = \frac{0.5}{\sqrt{0.5}} = \frac{\sqrt{2}}{2}.
  • We sort the documents by their similarity in descending order and then by their index in ascending order: sim0=1.0sim_0 = 1.0 (index 0), sim2=22sim_2 = \frac{\sqrt{2}}{2} (index 2), sim1=0.0sim_1 = 0.0 (index 1).
  • The top-2 documents are indices 0 and 2, so the output is: 0 2

Constraints:

  • 1 <= K <= N <= 100
  • 1 <= D <= 50
  • Cosine similarity: dot(a,b) / (norm(a) * norm(b))
solution.py

Test Results

0/0
Run code to see test results.
Top-K Retrieval - Easy | PixelBank