Best Match by Cosine Similarity
In a semantic search system each document is an embedding vector. Given a query vector and an array of document vectors docs (all the same length), return the index of the document with the highest cosine similarity to the query.
Cosine similarity is dot(a, b) / (|a| * |b|). Treat the similarity as 0 when either vector has length zero. If several documents tie (within 1e-9), return the smallest index. Return -1 when docs is empty.
Example 1
Input: query = [1,0], docs = [[0,1],[1,1],[2,0]] Output: 2 Explanation: Similarities are 0, 0.707 and 1.
Example 2
Input: query = [1,0], docs = [[1,0],[5,0]] Output: 0 Explanation: Both point the same way; the earlier one wins.
Constraints
- 0 <= docs.length <= 10^4
- 1 <= vector length <= 1024
Hint 1
Compute the query norm once, outside the loop.
Hint 2
Only replace the best index when the new similarity is strictly larger (beyond the tolerance).
Good practice for: AI Engineer (LLM & Generative AI), Machine Learning Engineer, Data Scientist, MLOps Engineer, Backend Developer
Run checks your code on 3 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.