K-Means
🎯 What is k-means? K-means splits a set of points into k groups. It keeps one center per group and repeats two steps: give each point to its nearest center, then move each center to the mean of its points. When no point changes group, it stops.
Waymo asked it in software engineer phone screens (first k points as the starting centers, stopping rule left to the candidate) and in a machine learning engineer phone screen that stressed NumPy broadcasting and asked for a better initialization (the question), and Nuro asked a machine learning engineer to implement it in a phone screen, followed by complexity questions (the question).
The Prompt
K-means is short enough to finish in a phone screen, so the interviewer grades the details: the rules you settle up front, how you vectorize, and what you do when a cluster goes empty.
"Given an array of points and a number k, cluster the points with k-means. Use the first k points as the starting centroids, and return each point's cluster."
Clarifying Questions
You: What does the input look like? An (n, d) float array, or a list of [row, col] pairs?
Interviewer: A list of 2D points is fine, but write it for any dimension.
You: If a point is equally close to two centroids, which one wins? And what if a cluster ends up empty?
Interviewer: Ties go to the lower cluster index. For an empty cluster, you decide; tell me what you chose.
You: When do I stop? I'd stop when no point changes cluster, with a cap on iterations.
Interviewer: That works. Cap it at 100.
You: What should I return, and can I assume 1 <= k <= n?
Interviewer: Labels of shape (n,) and the final centroids. Check k and raise if it's out of range.
What You'll Build
sq_dists(X, C) -> (n, k): squared distance from every point to every centroid.update_centroids(X, labels, C) -> (k, d): the mean of each cluster; an empty cluster keeps its centroid.kmeans(X, k, max_iters=100, init=None) -> (labels, C): the full loop, starting from the first k points unlessinitis given.inertia(X, labels, C) -> float: the sum of squared distances, used to test and to compare runs.
The Idea
K-means looks for the k centers that make points as close as possible to their own center. "Close" is measured
as the total squared distance, called the inertia. With X of shape (n, d), centroids C of shape (k, d) and
labels c of shape (n,):
J(c, C) = sum_i || X[i] - C[c[i]] ||^2
Lloyd's algorithm alternates two steps. Each one is the exact best choice for one variable while the other stays fixed, which is why the algorithm works at all.
- Assign. With
Cfixed, the best label for a point is its nearest centroid:c[i] = argmin_j ||X[i] - C[j]||^2. This needs the(n, k)matrix of squared distances. - Update. With
cfixed, the best centroid for a cluster is the mean of its points:C[j] = mean(X[c == j]), because the mean minimizes a sum of squared distances.
Neither step can raise J, and there are finitely many ways to label n points, so the loop always stops. It
stops at a local minimum, though, not necessarily the best clustering, which is why the starting centroids matter.
One iteration costs O(n k d); the distance matrix dominates.
Implementation
The goal is a version with no Python loop over points or clusters, and a distance matrix that fits in memory. Get there in three steps, and say out loud why you take each one.
Bad Solution: Python loops
Approach
Write the two steps literally: for each point, a list of distances to each centroid; for each cluster, the mean of its members. This is a fine thing to put down in the first ten minutes, and it becomes the reference for the tests.
import numpy as np
def kmeans_loops(points: list[list[float]], k: int, max_iters: int = 100) -> list[int]:
n = len(points)
centroids = [list(p) for p in points[:k]] # first k points
labels = [-1] * n
for _ in range(max_iters):
new_labels = []
for p in points: # assign: n * k * d Python steps
dists = [sum((a - b) ** 2 for a, b in zip(p, c)) for c in centroids]
new_labels.append(dists.index(min(dists))) # first minimum: lower index wins ties
if new_labels == labels:
break
labels = new_labels
for j in range(k): # update
members = [p for p, lab in zip(points, labels) if lab == j]
if members: # empty cluster: keep the old centroid
centroids[j] = [sum(col) / len(members) for col in zip(*members)]
return labels
Challenges
Every distance is an interpreted loop, so one iteration is n * k * d Python steps, and the update scans all
points once per cluster. On 100,000 points and 50 clusters that is minutes per run where NumPy takes well under a
second. An interviewer who mentions NumPy wants these loops gone.
Good Solution: broadcasting
Approach
Broadcasting computes every difference at once. X[:, None, :] is (n, 1, d) and C[None, :, :] is
(1, k, d), so their difference is (n, k, d); square and sum over the last axis. The update needs a sum and a
count per cluster: np.add.at adds each row of X into the row given by its label, and np.bincount counts the
labels.
def sq_dists_broadcast(X: np.ndarray, C: np.ndarray) -> np.ndarray:
diff = X[:, None, :] - C[None, :, :] # (n, k, d)
return (diff ** 2).sum(axis=-1) # (n, k)
def update_centroids(X: np.ndarray, labels: np.ndarray, C: np.ndarray) -> np.ndarray:
k, d = C.shape
sums = np.zeros((k, d))
np.add.at(sums, labels, X) # sums[labels[i]] += X[i]
counts = np.bincount(labels, minlength=k) # (k,)
new_C = C.copy() # empty clusters keep their centroid
filled = counts > 0
new_C[filled] = sums[filled] / counts[filled, None]
return new_C
Challenges
The update is now right and fast, but the distances build an (n, k, d) array. With n = 10^6, k = 100 and
d = 64 that is 6.4 billion floats, about 51 GB in float64. It is exact and easy to read, so it is a good answer
for small inputs, but expect the question "what if n is a million?"
Great Solution: the expanded square
Approach
Expand the square: ||x - c||^2 = ||x||^2 - 2 x.c + ||c||^2. The middle term for all pairs is one matrix
product, X @ C.T, and the other two broadcast as a column and a row. Memory drops to (n, k), and the matrix
product runs on optimized BLAS.
def sq_dists(X: np.ndarray, C: np.ndarray) -> np.ndarray:
x2 = (X ** 2).sum(axis=1)[:, None] # (n, 1)
c2 = (C ** 2).sum(axis=1)[None, :] # (1, k)
d2 = x2 - 2.0 * X @ C.T + c2 # (n, k)
return np.maximum(d2, 0.0) # rounding can make tiny distances negative
The full loop stops when labels repeat. At that point the centroids are means of the same groups, so nothing else can change; an exact test beats picking a tolerance.
def kmeans(X: np.ndarray, k: int, max_iters: int = 100, init: np.ndarray | None = None
) -> tuple[np.ndarray, np.ndarray]:
X = np.asarray(X, dtype=float) # (n, d)
n = X.shape[0]
if not 1 <= k <= n:
raise ValueError(f"need 1 <= k <= n, got k={k}, n={n}")
C = X[:k].copy() if init is None else np.asarray(init, dtype=float).copy() # (k, d)
labels = np.full(n, -1)
for _ in range(max_iters):
new_labels = sq_dists(X, C).argmin(axis=1) # (n,); argmin picks the lower index on ties
if np.array_equal(new_labels, labels):
break # no point moved: converged
labels = new_labels
C = update_centroids(X, labels, C)
return labels, C
def inertia(X: np.ndarray, labels: np.ndarray, C: np.ndarray) -> float:
return float(((X - C[labels]) ** 2).sum())
Challenges
The expansion loses precision when a point sits almost on a centroid: the three terms cancel and rounding can
leave something like -1e-12. That is harmless for argmin but breaks anything that takes a square root, so
clamp at zero. When even (n, k) is too big, compute the distances in chunks of rows (see the follow-ups).
Common Mistakes
sums[labels] += Xfor the update. Symptom: centroids come out too close to the origin. With repeated indices NumPy applies only one of the additions, so each sum holds one point but is divided by the full count. Fix:np.add.at, or a one-hot matrix product.- Dividing by a zero count. Symptom: a centroid turns into
NaN, and sinceargmintreatsNaNas the smallest value, every point jumps to it on the next pass. Fix: keep or reseed empty clusters. - Summing over the wrong axis. Symptom: a
(k,)or(n, d)result where you expected(n, k). Fix: write the shape in a comment on every line and run it once onn = 4, k = 2before the real data.
Testing It
Test three things: a case you can trace by hand, agreement with the loop version, and the property the algorithm guarantees. Start with four points, two near the origin and two far away, where the first-k start puts both centroids in the same corner:
X = np.array([[0, 0], [0, 1], [10, 10], [10, 11]], dtype=float)
labels, C = kmeans(X, 2)
assert labels.tolist() == [0, 0, 1, 1]
assert np.allclose(C, [[0, 0.5], [10, 10.5]])
Trace it out loud. The centroids start at (0, 0) and (0, 1), and the first assign gives [0, 1, 1, 1], so
centroid 1 moves to (6.67, 7.33). Now (0, 1) is far closer to centroid 0, the second assign gives
[0, 0, 1, 1], and the third changes nothing. This test catches a wrong stopping rule or a swapped axis.
Next, compare with the loop version on random data, check both distance functions agree, and check that inertia never rises from one iteration to the next. A rising inertia means the update is not computing true means.
rng = np.random.default_rng(0)
X = rng.normal(size=(300, 3))
labels, C = kmeans(X, 5)
assert labels.tolist() == kmeans_loops(X.tolist(), 5)
assert np.allclose(sq_dists(X, C), sq_dists_broadcast(X, C))
C_t, history = X[:5].copy(), []
for _ in range(20):
lab = sq_dists(X, C_t).argmin(axis=1)
history.append(inertia(X, lab, C_t))
C_t = update_centroids(X, lab, C_t)
assert all(b <= a + 1e-9 for a, b in zip(history, history[1:]))
Finally, the edge cases: duplicate starting points, k = n, and a bad k.
X = np.array([[0, 0], [0, 0], [5, 5]], dtype=float)
assert sq_dists(X, X[:2]).argmin(axis=1).tolist() == [0, 0, 0] # first pass: every tie -> 0
labels, C = kmeans(X, 2)
assert labels.tolist() == [1, 1, 0] # the empty cluster kept (0, 0) and won it back
assert np.allclose(C, [[5, 5], [0, 0]])
labels, _ = kmeans(np.eye(3), 3)
assert labels.tolist() == [0, 1, 2] # k = n: each point is its own cluster
try:
kmeans(np.eye(3), 4)
raise AssertionError("expected ValueError")
except ValueError:
pass
The duplicate case is worth walking through. Both centroids start at the origin, every point ties, and the first
pass leaves cluster 1 empty. Cluster 0 moves to (5/3, 5/3), cluster 1 stays at (0, 0) under the keep rule,
and on the next pass it takes the two origin points back.
Follow-ups
1) The first k points can be a bad start. How would you improve the initialization?
Show the problem first. Six points form two columns, at x = 0 and x = 10, with two more in the middle. If the
middle points come first, the centroids start one above the other, and k-means splits the data into a top row and
a bottom row, which is already a fixed point:
X = np.array([[5, 0], [5, 1], [0, 0], [0, 1], [10, 0], [10, 1]], dtype=float)
labels, C = kmeans(X, 2)
assert labels.tolist() == [0, 1, 0, 1, 0, 1] and inertia(X, labels, C) == 100.0
Splitting off the left column gives an inertia of 26.5. The fix is k-means++: pick the first centroid at random,
then pick each next one with probability proportional to its squared distance from the nearest centroid chosen so
far. Far points are likely picks, so the starts spread out, and the expected inertia is within O(log k) of the
optimum.
def kmeans_pp_init(X: np.ndarray, k: int, rng: np.random.Generator) -> np.ndarray:
n = X.shape[0]
C = [X[rng.integers(n)]]
d2 = sq_dists(X, np.array(C))[:, 0] # (n,) distance to nearest chosen centroid
for _ in range(1, k):
if d2.sum() == 0: # fewer distinct points than k
C.append(X[rng.integers(n)])
continue
C.append(X[rng.choice(n, p=d2 / d2.sum())])
d2 = np.minimum(d2, sq_dists(X, C[-1][None, :])[:, 0])
return np.array(C) # (k, d)
rng = np.random.default_rng(0)
runs = [kmeans(X, 2, init=kmeans_pp_init(X, 2, rng)) for _ in range(10)]
best_labels, best_C = min(runs, key=lambda r: inertia(X, *r))
assert inertia(X, best_labels, best_C) == 26.5
k-means++ is still random, and on this input some single runs end at 34.7. That is why the last lines matter: run several starts and keep the lowest inertia.
2) What is the time and memory complexity?
Time is O(n k d) per iteration times the number of iterations, which in practice is usually tens, though the
worst case is far larger. The update is O(n d). Memory is O(n d) for the data plus O(n k) for the distance
matrix, or O(n k d) with plain broadcasting. When n k doesn't fit, assign in chunks of rows, so the extra
memory is O(chunk * k):
def assign_chunked(X: np.ndarray, C: np.ndarray, chunk: int = 4096) -> np.ndarray:
return np.concatenate([sq_dists(X[s:s + chunk], C).argmin(axis=1)
for s in range(0, len(X), chunk)])
3) How do you choose k?
You can't just minimize inertia, because it always falls as k grows and reaches zero at k = n. Plot inertia
against k and look for the elbow where the gains flatten, or pick the k with the best silhouette score (how much
closer each point is to its own cluster than to the next one). Often k comes from the problem itself: the number
of depots, colors or speakers.
4) The data doesn't fit in memory. Now what?
Use mini-batch k-means. Sample a batch, assign it, and move each centroid toward its batch points with a
per-centroid rate of 1 / count, so each centroid is a running mean of every point it has seen. The result is a
little worse in inertia, but each step costs O(b k d) for a batch of b points.
def minibatch_step(C: np.ndarray, counts: np.ndarray, batch: np.ndarray) -> None:
labels = sq_dists(batch, C).argmin(axis=1)
for i, j in enumerate(labels):
counts[j] += 1
C[j] += (batch[i] - C[j]) / counts[j] # running mean, updated in place
What is Expected at Each Level?
Junior
A junior candidate should get a correct Lloyd's loop running, even if the first version uses Python loops, and trace a small example by hand. They should state a stopping rule and return labels in the agreed shape. It is fine if the interviewer has to point out the empty-cluster case, as long as the fix is quick and correct.
Mid-level
A mid-level candidate settles ties, empty clusters and stopping in the clarifying questions, then writes the
vectorized version without prompting: a broadcast or expanded-square distance matrix and an np.add.at update.
They test against a known answer and can give the per-iteration cost. When asked to improve the start, they
describe k-means++ and multiple restarts and can code k-means++ in a few minutes.
Senior
A senior candidate does all of that quickly and spends the rest on trade-offs. They explain why the loop converges and why only to a local minimum, the memory cost of broadcasting against the expanded square and its precision issue, and chunking or mini-batches for scale. They also know when k-means is the wrong tool: long thin clusters, rings and unscaled features break its round-cluster assumption, and a Gaussian mixture or a density method fits better.