Clustering prototypes show up constantly on Google and Waymo ML teams, and this screen (reported by candidates from both companies' coding rounds) rewards the same habit: writing a few lines of vectorized NumPy that stay correct when the data misbehaves. You must implement KMeans.fit(X, k) from scratch. It takes a float array of shape and returns integer cluster labels of shape
and centroids of shape
. Calling
sklearn.cluster.KMeans, scipy.cluster.vq, or scipy.spatial.distance.cdist is forbidden.
Initialization is fixed for this round: distinct rows of
X drawn at random, with k-means++ left as a follow-up. The interviewer cares less about the happy path than about three edge cases. A cluster can come out empty mid-run, the loop needs a defensible stopping rule, and a correct implementation must preserve specific invariants on every iteration.
Complete the 4 missing operations in the skeleton below and narrate the array shape after each line. Then state the algorithm's time complexity, explain how you would choose , and write a test that checks invariants rather than one hand-picked output.
Skeleton Code (Fill Blanks 1-4):
01 import numpy as np
02
03
04 class KMeans:
05 def __init__(self, max_iter: int = 100, tol: float = 1e-6, seed: int = 0):
06 self.max_iter, self.tol = max_iter, tol
07 self.rng = np.random.default_rng(seed)
08
09 def fit(self, X: np.ndarray, k: int):
10 n_samples, n_features = X.shape # X: (n_samples, n_features) float64
11 centroids = X[self.rng.choice(n_samples, size=k, replace=False)] # (k, n_features)
12 self.inertia_history = []
13 for it in range(self.max_iter):
14 # TODO (Blank 1): squared distances from every point to every
15 # centroid, shape (n_samples, k), no Python loops
16 sq_dists = ...
17 # TODO (Blank 2): index of the nearest centroid per point, (n_samples,)
18 labels = ...
19 self.inertia_history.append(sq_dists[np.arange(n_samples), labels].sum())
20 prev_centroids = centroids.copy()
21 # TODO (Blank 3): recompute each centroid as the mean of its
22 # points; an empty cluster must stay finite
23 ...
24 # TODO (Blank 4): stop when the centroids have converged
25 if ...:
26 break
27 self.centroids_, self.labels_, self.n_iter_ = centroids, labels, it + 1
28 return labels, centroids
Figure 1: the input and output contract is fixed, the random-row initialization is given, and the four steps inside the Lloyd loop are yours to write, with the interviewer probing empty clusters, the stopping rule, and the loop's invariants.
1Inspection Checklist (Where to Look)
(1) Broadcast Geometry: Align the point axis of X and the centroid axis of centroids so one subtraction covers every pair, then reduce over the feature axis only.
(2) Reduction Axis: The assignment must produce one label per point, and line 19 indexes sq_dists with exactly that shape.
(3) Empty-Cluster Contract: Decide what a centroid with zero members should be before writing the update, and keep every centroid finite.
(4) Stopping Rule: Compare the updated centroids with the snapshot on line 20 using an explicit tolerance, and remember that line 13 is the second guard.
2Visual Review Map (Figure 2)

Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shape it must produce; writing the operations that reach them is the exercise.
3Interviewer Nudge & Line Focus
Pin the input shape, output shape, and failure mode of each blank before writing the NumPy call:
X is (n_samples, n_features) and centroids is (k, n_features). Which singleton axes must you insert so the subtraction broadcasts to a 3-axis tensor, and which axis do you reduce? If n_samples == k, what does a plain X - centroids silently compute instead of raising?
sq_dists is (n_samples, k). Does the reduction collapse the point axis or the centroid axis, what shape would the other choice produce, and which index wins when two centroids sit at exactly the same distance?
X contains duplicate rows, two initial centroids can be identical. What does averaging a (0, n_features) array return, what happens to the next distance matrix once one centroid holds that value, and which two finite choices could you make instead?
Leave a Reply