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
KNN From Scratch
00:00
5 left

KNN From Scratch

HardPython

Problem

Develop Health needs a small, dependency-free classifier for categorizing patient records. Implement k-nearest neighbors (KNN) from scratch using Euclidean distance and majority voting.

Given training feature vectors, their labels, a query vector, and an integer k, return the predicted label for the query. Use the k training points with the smallest Euclidean distances. You may compare squared distances because the square root does not change their ordering.

If multiple labels receive the same highest vote count, return the label belonging to the closest neighbor. If distances are also equal, preserve the original training order.

Formal Specification

Implement predict_knn(points, labels, query, k), where points is a list of equal-length numeric feature vectors, labels is a list of strings parallel to points, query is one feature vector with the same dimension, and k is a positive integer. Return one string label.

Constraints

  • 1 <= len(points) <= 10^4
  • len(points) == len(labels)
  • 1 <= k <= len(points)
  • 1 <= len(query) == len(points[i]) <= 20
  • Feature values are integers or floating-point numbers
  • Labels are non-empty strings

Function Signature

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

Your question is KNN 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.