Skip to main content

Implement a k-nearest-neighbours classifier in NumPy: given labelled training points and a query point, predict the class of the query. For example, with class 0 points near (0, 0), class 1 points near (5, 5) and k = 3, the query (0.5, 0.5) should be class 0.

Coding rounds · Intermediate 2

Short answer

There is no training step: store the data. To predict, compute the distance from the query to every training point, take the k smallest with np.argpartition, and return the most common label among them. Each query costs O(n d). Scale the features first, because distance is sensitive to units.

Deeper answer

Clarify first: training X is n by d, queries are m by d, labels have length n, and k is at most n. Ask which distance to use, and how to break ties in the vote.

For one query q, d2 = ((X - q) ** 2).sum(axis=1) gives all squared distances. The square root is not needed, because it does not change the order. Then nearest = np.argpartition(d2, k - 1)[:k] finds the k closest in linear time without a full sort, and the prediction is the most common label among y[nearest]. For many queries, broadcast to an m by n distance matrix, and process the queries in batches if that matrix does not fit in memory.

Test a query equal to a training point, test k = 1, and compare the neighbours with a plain loop. Interviewers watch for unscaled features, where a column in rupees hides a column in years, and for an even k with two classes, which allows tied votes.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Classification

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.