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
Start free
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

Whenever you're ready, walk me through your approach or go straight to the code. The requirements are in the Question tab.

Sign up free to run or submit. Log in
Code
Sign up free to run your code. Your draft is saved.Run with a free accountLog inLn 2
Run your code to see test output here.