k-nearest-neighbour classifier

A free medium coding practice problem from ml. Solve it in JavaScript, TypeScript or Python and check your solution against fresh hidden tests — edge cases and random inputs — as often as you like.

Difficulty
Medium
Type
Function
Topic
Ml
Languages
JavaScript, TypeScript or Python

Problem

Classify points with k-NN. train is a list of [x, y, label] (integer coordinates, label a string), queries a list of [x, y], and 1 ≤ k ≤ len(train). For each query:
1. rank the training points by SQUARED Euclidean distance to the query, ties broken by lower index in train, and take the first k;
2. predict the label that occurs most often among them; if several labels tie for the most votes, predict the smallest of them (character-code order).

Return one label per query, in order. Coordinates |v| ≤ 1000, up to 2 000 training points and 200 queries.

Function signature

// JavaScript
function knnPredict(train, queries, k)

// TypeScript
function knnPredict(train: any, queries: any, k: any): any

// Python
def knn_predict(train, queries, k):

Examples

  1. knnPredict([[0,0,"red"],[1,0,"red"],[5,5,"blue"],[6,5,"blue"],[5,6,"blue"]], [[0,1],[5,4]], 3) → ["red","blue"]
  2. knnPredict([[0,0,"b"],[2,0,"a"]], [[1,0]], 2) → ["a"]

How checking works

Run your code against the examples above, then submit a check: it runs on the server against hidden tests built fresh each time, including edge cases and random inputs. Practice is untimed and never affects a verified score; when you are ready, take a graded coding challenge to earn a badge.

More practice problems

Next steps