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
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess 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
Get started
K Nearest Neighbors Implementation
00:00
5 left

K Nearest Neighbors Implementation

MediumPython

Problem

Pinterest uses nearest-neighbor methods as one signal for understanding and grouping visually similar Pins. Given labeled training vectors and one query vector, implement a K-Nearest Neighbors classifier that predicts the query's label efficiently.

Formal Specification

Implement knn_predict(points, labels, query, k). points is a list of n vectors, labels[i] is the label for points[i], and query is a vector with the same dimensionality. Return the label occurring most often among the k nearest points. Use squared Euclidean distance, since the square root does not affect ordering. If multiple labels have the same highest frequency, return the numerically smallest label.

When distances tie while selecting neighbors, prefer the point with the smaller original index. This makes the result deterministic.

Constraints

  • 1 <= k <= n <= 10^5
  • 1 <= len(query) = len(points[i]) <= 20
  • len(points) = len(labels)
  • -10^4 <= points[i][j], query[j] <= 10^4
  • Labels are integers

Function Signature

def knn_predict(points, labels, query, k):
Interviewer

Your question is K Nearest Neighbors Implementation. 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.