Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Vector Search from Scratch
00:00
5 left

Vector Search from Scratch

MediumPython

Problem

PRGX Global's spend analytics workflows can represent records as numeric vectors. Implement a basic vector search function that ranks candidate vectors by cosine similarity to a query vector and returns the indices of the top k matches.

Formal Specification

Given vectors, a list of n equal-length numeric vectors, a nonzero query vector, and an integer k, return a list of the k vector indices with the highest cosine similarity. Order results by decreasing similarity. If two vectors have the same similarity, place the smaller index first.

Compute similarity as:

cosine(a, b) = dot(a, b) / (magnitude(a) * magnitude(b))

Return only indices, not similarity scores. Do not use machine learning or vector-search libraries. A heap-based solution is encouraged so that retaining the best matches does not require sorting every vector.

Constraints

  • 1 <= len(vectors) <= 10^5
  • 1 <= len(query) <= 100
  • Every vector has the same dimension as query
  • Every vector and the query have nonzero magnitude
  • 1 <= k <= len(vectors)
  • Vector components are in [-10^4, 10^4]

Function Signature

def vector_search(vectors, query, k):
Interviewer

Your question is Vector Search from Scratch. Start with the requirements in the Question tab.

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.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.