In this article
Before you start
This page is one step of the machine learning algorithms learning path.
Why interviewers ask this
K-means is a natural first clustering question because the algorithm is short enough to explain in a minute, yet it has real failure modes. A candidate who only recites the steps shows memory. A candidate who explains why the loop stops, and why stopping is not the same as being right, shows understanding.
A weak answer says "pick k centers, assign, update" and ends. A strong answer names the objective, inertia, and says the loop reaches only a local minimum, so you restart it. A Staff-level answer adds how k is chosen without labels, why the starting centroids matter, and when the shape assumption breaks. Expect follow-ups such as "does it always converge?", "is the result optimal?" and "how do you pick k?". Each is answered below with numbers you can recompute.
K-means clustering from first principles
- K-means clustering
- K-means clustering is an unsupervised algorithm that partitions unlabeled data points into k groups by choosing k centers and repeatedly reassigning points to the nearest center, so that the total squared distance from each point to its own center becomes as small as the method can make it.
In plain words
Picture placing k pizza shops in a city so that every house is near a shop. Start with guesses. Each house picks its nearest shop. Then each shop moves to the middle of its houses. Repeat until no house switches. Each pass leaves the total squared walking distance the same or smaller, so the shops eventually stop moving.
The analogy breaks in one place. Real shops would cut walking distance, but k-means cuts squared distance, which punishes far-away houses much more.
In one precise sentence, k-means alternates between assigning points to their nearest centroid and replacing each centroid by the mean of its points, which lowers inertia until the assignments stop changing.
Step 1: Choose k and place the starting centroids
The loop starts from k initial centroids, and you choose k yourself. The scikit-learn documentation states that "this algorithm requires the number of clusters to be specified". The starting centroids are usually k data points picked at random, or points chosen by the k-means++ rule described below.
In the running example the data are six points on a line, at 0, 1, 10, 11, 20 and 21 (illustrative), with k equal to 2 and starting centroids at 0 and 1, a deliberately poor start.
Input: the data and k. Output: k centroids. You now know the loop's starting state; the next step uses it to form clusters.
Step 2: Assign every point to its nearest centroid
Each point is assigned to its nearest centroid, measured by squared Euclidean distance. The Stanford Computer Science 229 (CS229) notes write this as a minimum over the centroids.
In the example the point 1 sits exactly on the centroid at 1, so it joins that cluster together with 10, 11, 20 and 21, while the centroid at 0 keeps only the point 0.1 The inertia of this first assignment, measured with the centroids in use, is 942.1
Input: the points and the centroids. Output: one cluster label per point. If a point is equally close to two centroids, a fixed rule such as "take the lower-numbered one" settles it; any rule works if it is applied the same way every round. Assignment alone moves no centroid; that is the next step.
Step 3: Move each centroid to the mean of its points
Each centroid moves to the mean of its points. For a fixed assignment the mean is the point with the smallest sum of squared distances, so this move can only lower inertia. That is why the Stanford notes can show that the objective never rises.
In the example the cluster holding only 0 keeps its centroid at 0, and the cluster of 1, 10, 11, 20 and 21 moves its centroid to the mean, 12.6.1
Input: the clusters. Output: new centroids. Old assignments may now be wrong, because some points are closer to a moved centroid, which is why the loop has a fourth step.
Step 4: Repeat until assignments stop changing, and why it can get stuck
The loop stops when assignments stop changing. In the example, round two moves only the point 1, to the centroid at 0. The inertia is 135.64, and the new centroids are 0.5 and 15.5. Round three changes nothing and ends at an inertia of 101.5.1 Inertia fell from 942 to 135.64 to 101.5 and never rose. The Stanford notes show k-means is coordinate descent on the distortion J, which "must monotonically decrease, and the value of J must converge".
Convergence is not quality. The distortion is non-convex, so the loop can finish at a local minimum, a solution that no single reassignment or centroid move can improve even though a better one exists elsewhere. This poor start still reached the best two-cluster split (101.5), the same value as the elbow table below, so a bad start does not always mean a bad result. With three clusters it does: on the same points, starting at 0, 1 and 15 ends at an inertia of 101, while starting at 0, 10 and 20 ends at 1.5.1
Step-by-step description
- Pick k starting centroids.
- Each point joins its nearest centroid.
- Each centroid moves to its cluster mean.
- Stop if nothing changed, else assign again.
- The loop starts from k initial centroids.
- Each point is assigned to its nearest centroid.
- Each centroid moves to the mean of its points.
- The loop stops when assignments stop changing.
Why restarts and k-means++ reduce the risk of a poor result
Running k-means several times from different starts reduces the risk of a poor local minimum. As the scikit-learn documentation puts it, the computation is often done several times with different initializations. The KMeans reference says the final result is the best of n_init runs in terms of inertia. With n_init='auto' it uses 10 runs for random starts and 1 run for k-means++. So under scikit-learn's defaults (k-means++ start, n_init='auto') only one run is made; set n_init yourself if you want restarts.
K-means++ is a seeding method that selects the initial centroids one at a time, picking each new seed with probability proportional to its squared distance from the nearest seed already chosen, which speeds up convergence. It carries a proof: Arthur and Vassilvitskii show the expected cost is at most 8 times (ln k plus 2) times the optimal cost. For k equal to 10 that factor is 34.4207.1 It is a worst-case bound on expected cost, not a promise of the optimum.
Worked example: the elbow on inertia
Inertia keeps falling as k grows and reaches zero with six clusters, because with one cluster per point every distance is zero. So the lowest inertia cannot pick k. The elbow method is the habit of running k-means for several values of k, plotting inertia against k and choosing the bend where further clusters add little.
On the six example points, the best inertia is 401.5 with one cluster, 101.5 with two, 1.5 with three, 1.0 with four, 0.5 with five and 0 with six.1 After three clusters inertia barely moves. The bend is at three, matching the three visible pairs.
Text description of the diagram
- Inertia is 401.5 with one cluster, 101.5 with two and 1.5 with three.
- Inertia keeps falling as k grows and reaches zero with six clusters.
Worked example: the silhouette score
The silhouette score checks clusters without labels. For each point, a is the mean distance to the other points in its own cluster and b is the mean distance to the points of the next nearest cluster. The point's score is s equal to (b minus a) divided by the larger of a and b, as defined in the scikit-learn documentation, and the score is averaged over the points. A value close to one means b is much larger than a.
On the example points, the mean silhouette score is 0.8981 for the three-cluster solution and 0.6267 for the two-cluster solution.1 The higher score agrees with the elbow. When the two disagree, domain judgment about how many groups are useful decides.
What k-means assumes about the data
K-means assumes clusters that are roughly round and similar in spread. The scikit-learn documentation says inertia "makes the assumption that clusters are convex and isotropic" and so responds "poorly to elongated clusters, or manifolds with irregular shapes". In very high-dimensional spaces, Euclidean distances tend to become inflated.
The loop itself is a heuristic. Wikipedia's k-means++ page notes that finding an exact solution for arbitrary input is nondeterministic polynomial-time (NP) hard, that the standard approach, Lloyd's algorithm, frequently finds reasonable solutions quickly, and that its result can be arbitrarily bad compared with the optimum.
Because the mean is pulled by extreme points, outliers can drag a centroid. Distance to the nearest centroid is a rough outlier signal; see anomaly detection on a time series.
Knowing it is half the job. Saying it is the other half.
Interview Clozo is an AI interview copilot for real interview rounds: it hears the question and puts a strong answer on your screen, and you say it in your own words. See the features or how it works.
Start Free Trial →The Staff-level answer
How does K-means clustering work?
K-means splits unlabeled data into k clusters by minimizing inertia, the total squared distance from each point to its cluster's centroid. I choose k, pick starting centroids, ideally with k-means++, assign every point to its nearest centroid, then move each centroid to the mean of its points. I repeat until assignments stop changing. Inertia can only fall, so it converges, but only to a local minimum, so I run several starts and keep the lowest inertia. K is not learned: I choose it with the elbow on inertia and the silhouette score. It assumes round, similar clusters, so I scale features first and switch method for elongated shapes.
What makes it Staff-level: it states the objective, the local-minimum limit, the remedy and the shape assumption in under a minute. The spoken structure is loop first, then the limit, then the fixes.
The rubric
| Dimension | Weak answer | Strong answer | Staff answer |
|---|---|---|---|
| Correctness | Says it picks centers and groups points, with no objective | Names the assign and update steps and the inertia objective | Adds that the update uses the mean because it minimizes squared distance |
| Depth | Stops after one pass | Explains convergence as inertia never rising | Separates convergence from quality: a local minimum, and the exact problem is NP-hard |
| Trade-offs | Claims it finds the best clusters | Mentions restarts or k-means++ | Explains the bound on expected cost and the shape and scale assumptions |
| Communication | Lists steps in a rush | States the loop in order with one example | Gives the loop, the limit and the remedy in about a minute |
| Follow-up readiness | Has no way to pick k | Names the elbow | Pairs the elbow with the silhouette score and domain judgment |
Three variants of this question
How do you choose the number of clusters in k-means?
Run k-means for a range of k, plot inertia and look for the bend, then check the silhouette score. Inertia alone always falls as k grows, so add judgment about how many groups are useful.
Why does k-means need several random starts?
K-means reaches only a local minimum, and the start decides which one. The KMeans reference keeps the best of n_init runs by inertia.
What happens when the clusters are long or irregular?
K-means responds poorly, because inertia assumes convex, isotropic clusters. Change the features, or use a method that does not assume round clusters.
Common mistakes
- "K-means finds the best clusters." (wrong) It converges to a local minimum, and the exact problem is NP-hard. (right) "It finds a good local minimum, so I restart and keep the lowest inertia."
- "Pick the k with the lowest inertia." (wrong) Inertia falls as k grows, reaching zero when every point is its own cluster. (right) "I look for the elbow, check the silhouette score and use domain judgment."
- "K-means works on any cluster shape." (wrong) It assumes convex, isotropic clusters. (right) "It suits round, similar clusters; elongated shapes need another method."
- "K-means minimizes the distance to the center." (wrong) It minimizes squared distance, and the mean is the minimizer. (right) "It minimizes the sum of squared distances, which is why centroids are means."
- "K-means++ gives the optimal start." (wrong) It bounds only the expected cost. (right) "It improves starts and has a bound, and I still use restarts."
Follow-up questions
Does k-means always converge?
Yes. Inertia never rises and there are only finitely many ways to split the points into k groups, so the assignments must eventually stop changing, given a consistent tie-breaking rule. The objective converges, per the Stanford notes, but the scikit-learn documentation adds that this "may be to a local minimum". In practice scikit-learn may also stop earlier, on its tol or max_iter settings.
How expensive is k-means?
Each iteration computes the distance from every point to every centroid, so the cost grows with the number of points times k times the number of dimensions. The KMeans reference gives the average complexity as O(k n T), where n is the number of samples and T is the number of iterations. The worst case is far worse: it is super-polynomial in the input size, as Wikipedia's k-means++ page notes, a result the reference credits to Arthur and Vassilvitskii's "How slow is the k-means method?". On very large n, MiniBatchKMeans trades some accuracy for speed.
What is the difference between k-means and k-nearest neighbors?
K-nearest neighbors (KNN) predicts a label for a new point from the labels of its nearest labeled examples. K-means has no labels and only groups points. The k-means vs KNN page compares them.
How is k-means related to gradient descent?
K-means is exactly coordinate descent on the distortion, per the Stanford notes: it minimizes over the assignments, then over the centroids. The gradient descent page covers the neighboring method that follows slopes instead.
Should you scale features before k-means?
Usually yes, when features use different units: Euclidean distance lets features measured on large scales dominate the assignment. See feature engineering techniques for scaling and encoding.
What does k-means do with outliers?
It does not treat them specially. An outlier belongs to the nearest centroid and pulls that centroid toward itself, because the update is a mean.
- K-means alternates assigning points to the nearest centroid and moving each centroid to its cluster mean.
- It minimizes inertia, the sum of squared distances to the centroids.
- Inertia never rises, so the loop converges, but only to a local minimum.
- Restarts and k-means++ lower the risk of a poor result without removing it.
- Choose k with the elbow and the silhouette score, never with the lowest inertia.
- It assumes round clusters and distance-based features, so scale first.
Sources
- 2.3. Clustering (K-means section), scikit-learn documentation 1.9.1 — scikit-learn, 26 Oct 2026
- KMeans API reference, scikit-learn 1.9.1 — scikit-learn, 26 Oct 2026
- CS229 lecture notes: The k-means clustering algorithm — Stanford University (Andrew Ng), spring 2020 notes, 1 Jan 2020
- k-means++: The Advantages of Careful Seeding — Arthur and Vassilvitskii, SODA 2007, 1 Jan 2007
- K-means++ — Wikipedia, 26 Oct 2026