FastPrepRetrieve Vectors by Cosine Similarity

Retrieve Vectors by Cosine Similarity

Harvey logoHarvey● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given a nonzero query vector and nonzero candidate vectors of the same dimension, return the indices of the k candidates with greatest cosine similarity to the query.

Cosine similarity is dot(a,b) / (norm(a) * norm(b)). Sort by descending similarity and break exact ties by smaller candidate index.

Function

topKCosineMatches(query: double[], candidates: double[][], k: int) → int[]

Examples

Example 1

query = [1.0,0.0]candidates = [[1.0,0.0],[1.0,1.0],[-1.0,0.0]]k = 2return = [0,1]

The aligned vector ranks first, followed by the 45-degree vector.

Example 2

query = [1.0,1.0]candidates = [[2.0,0.0],[0.0,2.0],[3.0,3.0]]k = 3return = [2,0,1]

Candidates zero and one tie, so the smaller index comes first.

Example 3

query = [2.0]candidates = [[5.0],[-4.0]]k = 1return = [0]

Positive collinear vectors have cosine one.

Constraints

  • 1 <= candidates.length <= 100000.
  • 1 <= query.length <= 200, and every candidate has that length.
  • All coordinates are finite and have absolute value at most 10^6.
  • The query and every candidate have positive Euclidean norm.
  • Any two mathematically distinct cosine scores differ by more than 10^-9.
  • 1 <= k <= candidates.length.

More Harvey problems

See Harvey hiring insights
public int[] topKCosineMatches(double[] query, double[][] candidates, int k) {
    // Write your solution here.
}
query[1.0,0.0]
candidates[[1.0,0.0],[1.0,1.0],[-1.0,0.0]]
k2
expected[0,1]
Checking account…