Simple Algorithm
Machine Learning · Convergence · 28 min

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 O(log⁡k)\order{\log k} 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 kk and dd, exponential in the worst case, polynomial under smoothed analysis.
  • Prove the two cluster-level lemmas behind the 8(ln⁡k+2)8(\ln k+2) 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 x1,…,xn∈Rd\mathbf x_1,\dots,\mathbf x_n\in\R^d and kk, find centers C={c1,…,ck}C=\{\mathbf c_1,\dots,\mathbf c_k\} minimizing φ(C)=∑imin⁡j∥xi−cj∥2\varphi(C)=\sum_i\min_j\norm{\mathbf x_i-\mathbf c_j}^2. Write φOPT\varphi_{\mathrm{OPT}} 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 nn points that kk centers in Rd\R^d can induce in this way is O(nkd)\order{n^{kd}} (Inaba, Katoh & Imai, 1994), so for fixed kk and dd 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.

python
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]

O(kn2)\order{kn^2} time after sorting; prefix sums give each interval's cost in constant time, because ∑(x−xˉ)2=∑x2−(∑x)2/m\sum(x-\bar x)^2=\sum x^2-(\sum x)^2/m. On 0,2,4,100,2,4,10 it returns 5656 for k=1k=1 and 88 for k=2k=2.

DerivationThe reduction from densest cut (k = 2)
  1. ∥xu∥2=deg⁡(u),∥∑u∈Sxu∥2=cut(S,Sˉ)\norm{\mathbf x_u}^2=\deg(u),\qquad\Big\Vert\sum_{u\in S}\mathbf x_u\Big\Vert^2=\mathrm{cut}(S,\bar S)

    Densest cut asks, for a graph G=(V,E)G=(V,E) with nn vertices, for a split (S,Sˉ)(S,\bar S) maximizing cut(S,Sˉ)/(∣S∣ ∣Sˉ∣)\mathrm{cut}(S,\bar S)/(\abs S\,\abs{\bar S}); it is NP-hard. Embed vertex uu as xu∈R∣E∣\mathbf x_u\in\R^{\abs E}: orient each edge e={u,v}e=\{u,v\} arbitrarily and set xu[e]=1x_u[e]=1, xv[e]=−1x_v[e]=-1, all other coordinates 0. A sum over SS cancels on every edge with both endpoints in SS and keeps ±1\pm1 exactly on the cut edges:

  2. ∑u∈S∥xu−μS∥2=∑u∈Sdeg⁡(u)−cut(S,Sˉ)∣S∣\sum_{u\in S}\norm{\mathbf x_u-\boldsymbol\mu_S}^2=\sum_{u\in S}\deg(u)-\frac{\mathrm{cut}(S,\bar S)}{\abs S}

    The scatter of a group around its centroid is ∑u∈S∥xu∥2−1∣S∣∥∑u∈Sxu∥2\sum_{u\in S}\norm{\mathbf x_u}^2-\frac1{\abs S}\norm{\sum_{u\in S}\mathbf x_u}^2 (the centroid identity from the Descent lesson Clustering):

  3. φ(S,Sˉ)=2∣E∣−cut(S,Sˉ)(1∣S∣+1∣Sˉ∣)=2∣E∣−n cut(S,Sˉ)∣S∣ ∣Sˉ∣\varphi(S,\bar S)=2\abs E-\mathrm{cut}(S,\bar S)\Big(\frac1{\abs S}+\frac1{\abs{\bar S}}\Big)=2\abs E-n\,\frac{\mathrm{cut}(S,\bar S)}{\abs S\,\abs{\bar S}}

    Add the two clusters; the degrees sum to 2∣E∣2\abs E:

  4. arg min⁡Sφ(S,Sˉ)=arg max⁡Scut(S,Sˉ)∣S∣ ∣Sˉ∣\argmin_{S}\varphi(S,\bar S)=\argmax_{S}\frac{\mathrm{cut}(S,\bar S)}{\abs S\,\abs{\bar S}}

    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 ∣E∣\abs E grows with the input, consistent with the polynomial algorithm for fixed dd.

Check your understanding

For which of these families of k-means instances is an exact polynomial-time algorithm known?

  1. k=2k=2, with the dimension growing with the number of points
  2. Points in the plane, with kk growing with the number of points
  3. Points on a line, for any kk
  4. k=3k=3 in dimension nn
Show the answer

C. Points on a line, for any kk

On a line, optimal clusters are contiguous runs of sorted points, and dynamic programming finds the optimum in O(kn2)\order{kn^2} time. The other three are NP-hard: the first and last by the densest-cut reduction (for k=3k=3, 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 ε>0\varepsilon>0, approximating Euclidean k-means within a factor 1+ε1+\varepsilon is NP-hard when kk and dd grow (Awasthi, Charikar, Krishnaswamy & Sinop, 2015), so there is no polynomial-time approximation scheme (PTAS) in general. Schemes do exist when kk is fixed, in time linear in nn (Kumar, Sabharwal & Sen, 2010), and when dd 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 4+ε4+\varepsilon (Charikar, Cohen-Addad, Gao, Grandoni, Lee & van Wijland). Swap-based local search with pp simultaneous swaps reaches (3+2/p)2+ε(3+2/p)^2+\varepsilon, tending to 9+ε9+\varepsilon, and no local search with a fixed number of swaps does better than 9−ε9-\varepsilon 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 n34k34d8log⁡4n/σ6n^{34}k^{34}d^8\log^4 n/\sigma^6, 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.

Predict before you look

Four points sit at the corners of a 10×110\times1 rectangle, and k=2k=2. 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 55 from its center, so the cost is 4⋅52=1004\cdot5^2=100. It is a fixed point: a top corner is 55 from the top center and 26≈5.10\sqrt{26}\approx5.10 from the bottom one. The optimum pairs the left corners and the right corners, each point 0.50.5 from its center: cost 4⋅0.52=14\cdot0.5^2=1. For a w×hw\times h rectangle the ratio is (w/h)2(w/h)^2, 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 AA at a time, with centroid μA\boldsymbol\mu_A and optimal cost φOPT(A)=∑x∈A∥x−μA∥2\varphi_{\mathrm{OPT}}(A)=\sum_{\mathbf x\in A}\norm{\mathbf x-\boldsymbol\mu_A}^2, and asks what a seed that lands in AA costs AA.

DerivationLemma 1: a uniform seed costs twice the optimum, in expectation
  1. ∑x∈A∥x−a∥2=φOPT(A)+∣A∣ ∥a−μA∥2\sum_{\mathbf x\in A}\norm{\mathbf x-\mathbf a}^2=\varphi_{\mathrm{OPT}}(A)+\abs A\,\norm{\mathbf a-\boldsymbol\mu_A}^2

    For any center a\mathbf a, the centroid identity splits the cost of AA around a\mathbf a:

  2. Ea∼Unif(A)[∑x∈A∥x−a∥2]=1∣A∣∑a∈A∑x∈A∥x−a∥2=2 φOPT(A)\E_{\mathbf a\sim\mathrm{Unif}(A)}\Big[\sum_{\mathbf x\in A}\norm{\mathbf x-\mathbf a}^2\Big]=\frac1{\abs A}\sum_{\mathbf a\in A}\sum_{\mathbf x\in A}\norm{\mathbf x-\mathbf a}^2=2\,\varphi_{\mathrm{OPT}}(A)

    Average over a\mathbf a drawn uniformly from AA. The second term averages to ∑a∈A∥a−μA∥2=φOPT(A)\sum_{\mathbf a\in A}\norm{\mathbf a-\boldsymbol\mu_A}^2=\varphi_{\mathrm{OPT}}(A). This lemma covers the first seed:

DerivationLemma 2: a D² seed costs at most eight times the optimum, in expectation
  1. φ(A)=∑x∈Amin⁡(D(x),∥x−a∥)2\varphi(A)=\sum_{\mathbf x\in A}\min\big(D(\mathbf x),\norm{\mathbf x-\mathbf a}\big)^2

    Let D(x)D(\mathbf x) be the distance to the nearest current seed. Given that the new seed lands in AA, it is a\mathbf a with probability D(a)2/∑a′∈AD(a′)2D(\mathbf a)^2/\sum_{\mathbf a'\in A}D(\mathbf a')^2, and afterwards each point of AA pays the smaller of its old and new squared distances:

  2. D(a)2≤2∣A∣∑x∈AD(x)2+2∣A∣∑x∈A∥x−a∥2D(\mathbf a)^2\le\frac2{\abs A}\sum_{\mathbf x\in A}D(\mathbf x)^2+\frac2{\abs A}\sum_{\mathbf x\in A}\norm{\mathbf x-\mathbf a}^2

    The triangle inequality gives D(a)≤D(x)+∥x−a∥D(\mathbf a)\le D(\mathbf x)+\norm{\mathbf x-\mathbf a}, so D(a)2≤2D(x)2+2∥x−a∥2D(\mathbf a)^2\le2D(\mathbf x)^2+2\norm{\mathbf x-\mathbf a}^2 for every x\mathbf x. Average over x∈A\mathbf x\in A:

  3. E[φ(A)]≤4∣A∣∑a∈A∑x∈A∥x−a∥2=8 φOPT(A)\E[\varphi(A)]\le\frac4{\abs A}\sum_{\mathbf a\in A}\sum_{\mathbf x\in A}\norm{\mathbf x-\mathbf a}^2=8\,\varphi_{\mathrm{OPT}}(A)

    Substitute into E[φ(A)]=∑aD(a)2∑a′D(a′)2 φ(A)\E[\varphi(A)]=\sum_{\mathbf a}\frac{D(\mathbf a)^2}{\sum_{\mathbf a'}D(\mathbf a')^2}\,\varphi(A). In the first term the ratio of sums is 1 and min⁡(⋅)2≤∥x−a∥2\min(\cdot)^2\le\norm{\mathbf x-\mathbf a}^2; in the second, ∑xmin⁡(⋅)2≤∑xD(x)2\sum_{\mathbf x}\min(\cdot)^2\le\sum_{\mathbf x}D(\mathbf x)^2 cancels the denominator. Both terms are at most 2∣A∣∑a∑x∥x−a∥2\frac2{\abs A}\sum_{\mathbf a}\sum_{\mathbf x}\norm{\mathbf x-\mathbf a}^2, 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 D2D^2 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 k−1k-1 later seeds costs a harmonic-number factor of at most 2+ln⁡k2+\ln k, which with Lemma 2 gives 8(ln⁡k+2)8(\ln k+2).

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 k(x,z)=⟨φ(x),φ(z)⟩k(\mathbf x,\mathbf z)=\langle\varphi(\mathbf x),\varphi(\mathbf z)\rangle without computing φ\varphi. The distance from a point to a cluster's implicit centroid uses only the Gram matrix:

∥φ(xi)−μj∥2=k(xi,xi)−2∣Cj∣∑l∈Cjk(xi,xl)+1∣Cj∣2∑l,m∈Cjk(xl,xm).\norm{\varphi(\mathbf x_i)-\boldsymbol\mu_j}^2=k(\mathbf x_i,\mathbf x_i)-\frac2{\abs{C_j}}\sum_{l\in C_j}k(\mathbf x_i,\mathbf x_l)+\frac1{\abs{C_j}^2}\sum_{l,m\in C_j}k(\mathbf x_l,\mathbf x_m).

Each iteration costs O(n2)\order{n^2} 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 PP with finite second moment, and the population objective as EPmin⁡j∥x−cj∥2\E_P\min_j\norm{\mathbf x-\mathbf c_j}^2. 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 ε\varepsilon-separated when φOPT,k≤ε2 φOPT,k−1\varphi_{\mathrm{OPT},k}\le\varepsilon^2\,\varphi_{\mathrm{OPT},k-1}, meaning the best kk-clustering is much cheaper than the best (k−1)(k-1)-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 1±ε1\pm\varepsilon for every choice of kk 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 O(log⁡k)\order{\log k} 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 k=2k=2 in growing dimension (a reduction from densest cut) and in the plane for growing kk, but polynomial for fixed kk and dd and exactly solvable in one dimension by dynamic programming.
  • It is APX-hard in general, admits approximation schemes when kk or dd is fixed, and has constant-factor approximations (5.912 in 2022, 4+ε4+\varepsilon in 2026); swap-based local search reaches 9+ε9+\varepsilon.
  • Lloyd's algorithm terminates within O(nkd)\order{n^{kd}} 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 8(ln⁡k+2)8(\ln k+2) times the optimum in expectation, on every data set, because a D2D^2 seed costs each optimal cluster at most 8 times its optimum; the Θ(log⁡k)\Theta(\log k) 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.

Question 1

Which statement about the computational complexity of k-means is correct?

  1. It is polynomial for every fixed kk, because Lloyd's algorithm terminates
  2. It is NP-hard only for points in the plane
  3. It is NP-hard for k=2k=2 when the dimension grows with the input, yet polynomial when both kk and dd are fixed
  4. It is NP-hard even in one dimension
Show the answer

C. It is NP-hard for k=2k=2 when the dimension grows with the input, yet polynomial when both kk and dd are fixed

The densest-cut reduction embeds a graph in dimension ∣E∣\abs E, so 2-means is NP-hard once dd is part of the input. With kk and dd both fixed, enumerating the O(nkd)\order{n^{kd}} Voronoi partitions is polynomial, and in one dimension dynamic programming solves any kk.

Question 2

In what sense does k-means++ guarantee E[φ]≤8(ln⁡k+2) φOPT\E[\varphi]\le8(\ln k+2)\,\varphi_{\mathrm{OPT}}?

  1. With high probability, for the clustering after Lloyd's iterations converge
  2. In expectation over the random seeding, for the seeds alone, on every data set
  3. Deterministically, for well-separated data only
  4. 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.

Question 3

In the smoothed analysis of Lloyd's algorithm, what is random?

  1. The initial centers
  2. The order in which points are processed
  3. The number of clusters kk
  4. 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 σ\sigma; the bound is on the expected number of iterations, maximized over the adversary's choice. Polynomial dependence on nn and 1/σ1/\sigma means exponential instances are knife-edge constructions.

Question 4

A cluster consists of the points 0,2,40, 2, 4 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?

  1. 8
  2. 16
  3. 20
  4. 24
Show the answer

B. 16

Around the centroid 2 the cost is 4+0+4=84+0+4=8, and Lemma 1 says a uniform center costs twice that in expectation. Directly: centers at 0, 2 and 4 cost 2020, 88 and 2020, which average to 1616.

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).