Skip to main content

Implement k-means clustering in NumPy: given n points and k, return the centroids and a cluster label for each point. For example, the points 1, 2, 10 and 11 with k = 2 should end with centroids 1.5 and 10.5.

Coding rounds · Intermediate 2

Short answer

Pick k starting centroids from the data. Repeat two steps: assign each point to its nearest centroid, then move each centroid to the mean of its points. Stop when the assignments no longer change or after a maximum number of rounds. Each round costs O(n k d).

Deeper answer

Clarify first: X is n by d, k is at most n, and the features should be on a similar scale, because k-means uses Euclidean distance.

Initialise by choosing k distinct rows at random, or with k-means++, which spreads the starting points out. The assignment step computes all squared distances by broadcasting, d2 = ((X[:, None, :] - C[None, :, :]) ** 2).sum(axis=2), and takes labels = d2.argmin(axis=1). The update step sets each centroid to X[labels == j].mean(axis=0). If a cluster has no points, that mean is NaN, so keep the old centroid or move it to a random point. Stop when the centroids no longer move.

Each round lowers the sum of squared distances or leaves it unchanged, so the loop always ends, but only at a local optimum. Run it from several seeds and keep the result with the lowest total. Test on two well-separated groups. Interviewers watch for the empty cluster, for no stopping rule, and for a square root that argmin does not need.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

Unsupervised learning

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.