Rank Vectors by Cosine Similarity
Given a query vector and a list of candidate vectors of the same dimension, rank the candidates by cosine similarity to the query, most similar first. Return the candidates' indices in that order; break ties by the smaller index.
Cosine similarity is dot(a, b) / (|a| |b|). Define the similarity to a zero-length vector (all components 0) as 0.
query = [1, 0] vectors = [[0, 1], [2, 0], [1, 1], [-1, 0]] -> [1, 2, 0, 3] // similarities 1, 0.707, 0, -1
The sort is part of the task: do not rely on a library's top-k.
Hints
Hint 1
Compute the query's magnitude once; recomputing it per candidate is the classic wasted work here.
Hint 2
Score as (similarity, index) pairs so the sort keeps the mapping back to the inputs, then sort by similarity descending and index ascending.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.