Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

K-Nearest Neighbors From Scratch

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

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

Implement the core prediction step of a k-nearest neighbors classifier for an Outgive machine learning workflow. Given labeled training samples and one query sample, return the class represented most often among the query's k nearest neighbors.

Use Euclidean distance over all feature dimensions. If multiple classes have the same frequency among the selected neighbors, return the lexicographically smallest class label. When distances are equal, sort the tied samples by their label before selecting neighbors, ensuring deterministic behavior.

Formal Specification

Implement knn_predict(train_features, train_labels, query, k), where train_features is a list of numeric feature vectors, train_labels is a list of strings with one label per vector, query is a numeric feature vector with the same dimension, and k is a positive integer. Return one string containing the predicted class label.

Constraints

  • 1 <= len(train_features) <= 10^4
  • Every feature vector has the same positive dimension as query
  • len(train_features) == len(train_labels)
  • 1 <= k <= len(train_features)
  • Feature values are integers or floats in [-10^6, 10^6]
  • Labels are non-empty strings

Function Signature

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