K-Nearest Neighbors
📍 What is k-nearest neighbors? K-nearest neighbors (KNN) predicts for a new point by looking at the k training points closest to it. For classification it takes a vote among their labels; for regression it averages their values. There is no training step: the model is the training data, and all the work happens at prediction time.
KNN is a common warm-up in ML coding rounds because the whole algorithm is one distance matrix and one top-k, so the interviewer can grade vectorization, memory and tie handling in twenty minutes.
The Prompt
The interviewer expects a correct answer quickly, so the score comes from the details: no Python loops over points, a top-k that doesn't sort everything, and rules for ties that you state before you code.
"Implement k-nearest neighbors classification. Given training points with labels and a batch of query points, return the predicted label for each query."
Clarifying Questions
You: What are the shapes? I'll assume X_train is (n, d), y_train is (n,) with integer labels
0..C-1, and the queries are (m, d).
Interviewer: Yes. Use Euclidean distance.
You: How should ties be broken? There are two kinds: two training points at the same distance at the edge of the top k, and a vote where two labels get the same count.
Interviewer: Distance ties go to the lower training index. For a tied vote, pick the smallest label.
You: Can k be larger than n? And should a query that is also a training point count itself?
Interviewer: Raise if k > n. The queries are separate from the training set.
You: How big can the data be?
Interviewer: Write it for the batch first. Then tell me what happens with a million training points.
What You'll Build
sq_dists(Q, X) -> (m, n): squared distances from every query to every training point.knn_indices(Q, X, k) -> (m, k): indices of the k nearest training points, nearest first, ties to the lower index.knn_classify(Q, X, y, k) -> (m,): the majority label, ties to the smallest label.knn_regress(Q, X, y, k) -> (m,): the mean of the neighbors' values.