k-Means: Hardness & Guarantees
NP-hardness, Lloyd’s algorithm and k-means++.
Lloyd's algorithm is among the most used procedures in data analysis, yet the problem it attacks is NP-hard even for two clusters, the algorithm can need exponentially many iterations, and its answer can be arbitrarily worse than the best one. This lesson proves the hardness, explains why the algorithm is fast in practice anyway, and proves the lemmas behind the guarantee that made k-means++ the default.
What you’ll learn
- Prove that 2-means is NP-hard in general dimension by a reduction from densest cut, and solve the one-dimensional problem exactly by dynamic programming.
- Bound the number of iterations of Lloyd's algorithm: polynomial for fixed and , exponential in the worst case, polynomial under smoothed analysis.
- Prove the two cluster-level lemmas behind the bound for k-means++, and state the matching lower bound.
- Survey approximation algorithms and their limits, kernel k-means, separation conditions under which Lloyd-type methods provably succeed, and the statistical consistency of k-means.
How hard is k-means?
The k-means problem: given and , find centers minimizing . Write for the optimum. Two structural facts organize what follows. Every optimal clustering is a Voronoi partition: each point belongs to the cell of its nearest optimal center, and each center is the centroid of its cell. And the number of distinct partitions of points that centers in can induce in this way is (Inaba, Katoh & Imai, 1994), so for fixed and the optimum can be found in polynomial time by enumerating them.
In one dimension, Voronoi cells are intervals, so optimal clusters are runs of consecutive points in sorted order, and dynamic programming over prefixes finds the exact optimum.
def kmeans_1d(xs, k):
xs = sorted(xs)
n = len(xs)
S, Q = [0.0], [0.0] # prefix sums of x and x^2
for x in xs:
S.append(S[-1] + x)
Q.append(Q[-1] + x * x)
def cost(i, j): # within-cluster sum of squares of xs[i:j]
s, m = S[j] - S[i], j - i
return Q[j] - Q[i] - s * s / m
best = [[float('inf')] * (n + 1) for _ in range(k + 1)]
best[0][0] = 0.0
for c in range(1, k + 1): # c clusters covering xs[:j]
for j in range(c, n + 1):
best[c][j] = min(best[c - 1][i] + cost(i, j) for i in range(c - 1, j))
return best[k][n]time after sorting; prefix sums give each interval's cost in constant time, because . On it returns for and for .
Densest cut asks, for a graph with vertices, for a split maximizing ; it is NP-hard. Embed vertex as : orient each edge arbitrarily and set , , all other coordinates 0. A sum over cancels on every edge with both endpoints in and keeps exactly on the cut edges:
The scatter of a group around its centroid is (the centroid identity from the Descent lesson Clustering):
Add the two clusters; the degrees sum to :
So the best 2-means clustering of the embedded points is the densest cut, and a polynomial-time algorithm for 2-means would solve an NP-hard problem. The dimension grows with the input, consistent with the polynomial algorithm for fixed .
For which of these families of k-means instances is an exact polynomial-time algorithm known?
- , with the dimension growing with the number of points
- Points in the plane, with growing with the number of points
- Points on a line, for any
- in dimension
Show the answer
C. Points on a line, for any
On a line, optimal clusters are contiguous runs of sorted points, and dynamic programming finds the optimum in time. The other three are NP-hard: the first and last by the densest-cut reduction (for , add a far-away point that must get its own center), the second by the planar reduction of Mahajan, Nimbhorkar & Varadarajan.
Approximation fares better, but not arbitrarily well. For some constant , approximating Euclidean k-means within a factor is NP-hard when and grow (Awasthi, Charikar, Krishnaswamy & Sinop, 2015), so there is no polynomial-time approximation scheme (PTAS) in general. Schemes do exist when is fixed, in time linear in (Kumar, Sabharwal & Sen, 2010), and when is fixed, by local search (Cohen-Addad, Klein & Mathieu, 2019; Friggstad, Rezapour & Salavatipour, 2019). For general instances, primal–dual algorithms built on a linear-programming relaxation achieve constant factors: 6.357 (Ahmadian, Norouzi-Fard, Svensson & Ward, 2020) and then 5.912 (Cohen-Addad, Esfandiari, Mirrokni & Narayanan, 2022); a 2026 algorithm analyzed by LP dual fitting reaches (Charikar, Cohen-Addad, Gao, Grandoni, Lee & van Wijland). Swap-based local search with simultaneous swaps reaches , tending to , and no local search with a fixed number of swaps does better than in high dimension (Kanungo, Mount, Netanyahu, Piatko, Silverman & Wu, 2004).
How long does Lloyd's algorithm run, and how bad can it end?
Smoothed analysis, introduced by Spielman and Teng to explain the simplex method, asks for the worst case of the expected cost under a small random perturbation of an adversarial input. A polynomial smoothed bound says that the exponential instances are fragile: almost any tiny jitter destroys them. The proven exponents are large (the full arXiv version of the paper states an expected number of iterations of order , and its authors did not try to optimize it), so the result explains the qualitative picture rather than the few dozen iterations seen in practice.
Speed is not the real weakness; quality is. A fixed point of Lloyd's algorithm can be arbitrarily worse than the optimum, even with four points.
Four points sit at the corners of a rectangle, and . Lloyd's algorithm is started with one center at the midpoint of each long side, so it pairs the two top corners and the two bottom corners. It stops immediately. How many times the optimal cost is the cost of this fixed point?
Show the answer
100
Each corner is from its center, so the cost is . It is a fixed point: a top corner is from the top center and from the bottom one. The optimum pairs the left corners and the right corners, each point from its center: cost . For a rectangle the ratio is , unbounded. No assign or update step escapes, but one swap of a center does, which is why local search and good seeding matter.
Why k-means++ works
The proof looks at one optimal cluster at a time, with centroid and optimal cost , and asks what a seed that lands in costs .
For any center , the centroid identity splits the cost of around :
Average over drawn uniformly from . The second term averages to . This lemma covers the first seed:
Let be the distance to the nearest current seed. Given that the new seed lands in , it is with probability , and afterwards each point of pays the smaller of its old and new squared distances:
The triangle inequality gives , so for every . Average over :
Substitute into . In the first term the ratio of sums is 1 and ; in the second, cancels the denominator. Both terms are at most , and Lemma 1 finishes:
The remaining step is an induction on the number of optimal clusters that no seed has hit yet. A seed can be wasted on an already-covered cluster, but sampling makes that unlikely while the uncovered clusters still hold much of the current cost, because their points are far from every seed. Summing the expected waste over the later seeds costs a harmonic-number factor of at most , which with Lemma 2 gives .
The guarantee holds in expectation, for the seeds alone, on every data set; Lloyd's iterations can only improve on it. Variants keep it at scale: k-means|| samples many candidates per round and needs only a logarithmic number of rounds (Bahmani, Moseley, Vattani, Kumar & Vassilvitskii, 2012).
Kernels, statistics and the frontier
Kernel k-means. The pairwise form of the objective needs only inner products, so k-means runs in the feature space of any kernel without computing . The distance from a point to a cluster's implicit centroid uses only the Gram matrix:
Each iteration costs once the Gram matrix is known, and with an RBF kernel the clusters need not be convex in the input space. With suitable point weights and a kernel built from a similarity graph, the weighted kernel k-means objective is equivalent to normalized cut (Dhillon, Guan & Kulis, 2004, 2007), so k-means-style iterations can optimize graph cuts without computing eigenvectors; the Convergence lesson Spectral Clustering takes the eigenvector route.
Statistics. Treat the points as i.i.d. draws from a distribution with finite second moment, and the population objective as . Pollard (1981) proved that, under a uniqueness condition on the optimal population centers, the empirical optimal centers converge to them almost surely: k-means is strongly consistent. Its target is the population objective, not "the true clusters", which is why k-means splits a single elongated Gaussian and cannot recover nonconvex groups however much data it sees.
Beyond the worst case. Practice suggests that real instances are easier than hard ones, and several conditions make this precise. Ostrovsky, Rabani, Schulman & Swamy (2012) call data -separated when , meaning the best -clustering is much cheaper than the best -clustering, which is the sharp drop practitioners look for in an elbow plot. On such data, Lloyd-type iterations started from a careful probabilistic seeding quickly reach provably near-optimal clusterings. Coresets compress the data: small weighted point sets whose cost approximates the full cost within a factor for every choice of centers (Har-Peled & Mazumdar, 2004), which brings k-means to streams and to data too large to store.
Think first k-means is NP-hard, yet scikit-learn runs it on millions of points in seconds. Is there a contradiction?
No. NP-hardness is about computing the exact optimum on worst-case inputs. Lloyd's algorithm with k-means++ seeding returns a fixed point, not the optimum, with an guarantee in expectation. Its running time is polynomial in the smoothed sense, and on data with a clear cluster structure Lloyd-type methods provably find near-optimal solutions. Hard instances exist, but they are carefully constructed, and small perturbations destroy them.
Key takeaways
- k-means is NP-hard for in growing dimension (a reduction from densest cut) and in the plane for growing , but polynomial for fixed and and exactly solvable in one dimension by dynamic programming.
- It is APX-hard in general, admits approximation schemes when or is fixed, and has constant-factor approximations (5.912 in 2022, in 2026); swap-based local search reaches .
- Lloyd's algorithm terminates within iterations, can take exponentially many in the worst case even in the plane, and is polynomial under smoothed analysis; its fixed points can be arbitrarily worse than the optimum.
- k-means++ seeding costs at most times the optimum in expectation, on every data set, because a seed costs each optimal cluster at most 8 times its optimum; the rate is tight.
- Kernel k-means needs only a Gram matrix and connects to normalized cuts; Pollard's theorem makes k-means consistent for its population objective; separation conditions and coresets explain and extend its practical success.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which statement about the computational complexity of k-means is correct?
- It is polynomial for every fixed , because Lloyd's algorithm terminates
- It is NP-hard only for points in the plane
- It is NP-hard for when the dimension grows with the input, yet polynomial when both and are fixed
- It is NP-hard even in one dimension
Show the answer
C. It is NP-hard for when the dimension grows with the input, yet polynomial when both and are fixed
The densest-cut reduction embeds a graph in dimension , so 2-means is NP-hard once is part of the input. With and both fixed, enumerating the Voronoi partitions is polynomial, and in one dimension dynamic programming solves any .
In what sense does k-means++ guarantee ?
- With high probability, for the clustering after Lloyd's iterations converge
- In expectation over the random seeding, for the seeds alone, on every data set
- Deterministically, for well-separated data only
- On average over random data sets drawn from a Gaussian mixture
Show the answer
B. In expectation over the random seeding, for the seeds alone, on every data set
The bound averages over the seeding's own randomness and holds for every input, with no assumption on the data. It concerns the seeds before any Lloyd iteration, and iterations can only lower the cost. A single run can be worse, which is why practitioners still keep the best of a few runs.
In the smoothed analysis of Lloyd's algorithm, what is random?
- The initial centers
- The order in which points are processed
- The number of clusters
- Small Gaussian perturbations of the input points
Show the answer
D. Small Gaussian perturbations of the input points
An adversary picks the input, then each point is perturbed by independent Gaussian noise of standard deviation ; the bound is on the expected number of iterations, maximized over the adversary's choice. Polynomial dependence on and means exponential instances are knife-edge constructions.
A cluster consists of the points on a line. If a center is placed at one of them chosen uniformly at random, what is the expected cost of the cluster around that center?
- 8
- 16
- 20
- 24
Show the answer
B. 16
Around the centroid 2 the cost is , and Lemma 1 says a uniform center costs twice that in expectation. Directly: centers at 0, 2 and 4 cost , and , which average to .
Further reading
- S. P. Lloyd, "Least squares quantization in PCM," IEEE Transactions on Information Theory 28(2), 129–137 (1982).
- D. Arthur & S. Vassilvitskii, "k-means++: the advantages of careful seeding," Proceedings of the 18th Annual ACM-SIAM Symposium on Discrete Algorithms (SODA), 1027–1035 (2007).
- D. Aloise, A. Deshpande, P. Hansen & P. Popat, "NP-hardness of Euclidean sum-of-squares clustering," Machine Learning 75(2), 245–248 (2009).
- A. Vattani, "k-means requires exponentially many iterations even in the plane," Discrete & Computational Geometry 45(4), 596–616 (2011).
- D. Arthur, B. Manthey & H. Röglin, "Smoothed analysis of the k-means method," Journal of the ACM 58(5), article 19 (2011).