Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Cosine Similarity Search Function

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Cosine Similarity Search Function. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

RBC NOMI may compare an embedding for a new customer interaction with stored embeddings to retrieve the most relevant matches. Implement an exact similarity search using cosine similarity.

Given a query vector, a list of candidate vectors, and an integer k, return the indices of the k candidates with the highest cosine similarity to the query. Return indices in descending similarity order. If two candidates have equal similarity, place the smaller index first.

For vectors a and b, cosine similarity is:

(a · b) / (||a|| × ||b||)

If either vector has zero magnitude, define its similarity as 0. All vectors have the same positive dimension, and 1 <= k <= number of candidates.

Formal Specification

  • Input: query, a list of real numbers; vectors, a list of equal-length real-number lists; k, a positive integer.
  • Output: A list of exactly k integer indices identifying the most similar candidate vectors.

Constraints

  • 1 <= len(vectors) <= 10^5
  • 1 <= len(query) = len(vectors[i]) <= 256
  • 1 <= k <= len(vectors)
  • Vector components have absolute value at most 10^4
  • If either vector has zero magnitude, its similarity is defined as 0
  • Ties are resolved by smaller candidate index

Function Signature

def cosine_search(query, vectors, k):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output