Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Basic Vector Search Index

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

Your question is Basic Vector Search Index. 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 stores documents as numeric embedding vectors. Given a collection of document embeddings and a query embedding, return the indices of the k documents with the highest cosine similarity to the query.

Formal Specification

Implement cosine_search(vectors, query, k), where:

  1. vectors is a non-empty list of equal-length lists of real numbers.
  2. query is a list of real numbers with the same dimension as every vector.
  3. k is an integer between 1 and len(vectors).
  4. The function returns a list of k integer indices, ordered from highest similarity to lowest.
  5. If two vectors have equal similarity, return the smaller index first.
  6. The cosine similarity is dot(a, b) / (||a|| * ||b||). If either vector has zero magnitude, define its similarity as 0.0.

The implementation should compute each similarity without modifying the input vectors. Focus on correctness and clear handling of zero vectors.

Constraints

  • 1 <= len(vectors) <= 10^5
  • 1 <= len(query) <= 256
  • Every vector has the same dimension as query
  • All components are finite real numbers
  • 1 <= k <= len(vectors)

Function Signature

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