K-Means Clustering: Assignment, Update, and Convergence
Arrays & HashingAuto-graded · 15 test casesLast updated
Tests ability to implement the full k-means loop — initialization, Euclidean assignment, centroid update, convergence check, and empty-cluster handling — in plain Python.
K-Means Clustering: Assignment, Update, and Convergence
Given a set of points in d-dimensional space, partition them into exactly k clusters by implementing the k-means algorithm from scratch. Use only the Python standard library — no third-party packages of any kind.
Task
Write a function that receives a list of points and returns two things:
- Centroids — a list of k points (each a list of
floats) representing the final cluster centers. - Labels — a list of n integers, one per input point, where each integer is in
[0, k)and identifies which cluster that point belongs to.
Algorithm Rules
Initialization
Select k distinct starting centroids by sampling k unique indices from range(n) without replacement. Use random.Random(seed) and call its .sample(range(n), k) method to obtain those indices. Convert the chosen points to float.
Assignment step
For every point, compute its squared Euclidean distance to each centroid and assign the point to the closest one. Break ties by choosing the centroid with the smaller index.
Update step
Recompute each centroid as the coordinate-wise mean of all points assigned to it. If a cluster ends up with no points assigned, leave its centroid unchanged from the previous iteration.
Convergence
After each update, check both of the following conditions and stop if either is true:
- The label assignments are identical to those from the previous iteration.
- The maximum Euclidean displacement of any centroid (current position vs. previous position) is ≤
tol.
Also stop after max_iters iterations regardless of convergence.
Constraints
1 <= k <= n, wheren = len(points).- All points share the same dimension
d >= 1. 1 <= max_iters <= 10_000.0 < tol <= 1.0.seedis eitherNoneor a non-negative integer; results must be fully reproducible whenseedis provided.- Point coordinates are finite floats.
k = 1andk = nare valid inputs and must be handled correctly.- Do not import NumPy or any other third-party library; use only Python's standard library (
math,random, etc.).
Examples
Example 1
Input: kmeans([[1, 1], [1.5, 2], [3, 4], [5, 7], [3.5, 5], [4.5, 5], [3.5, 4.5]], 2, 100, 0.000001, 0)
Output: [[[1.25, 1.5], [3.9, 5.1]], [0, 0, 1, 1, 1, 1, 1]]
Example 2
Input: kmeans([[0], [0], [10], [10]], 2, 100, 0.000001, 1)
Output: [[[0], [10]], [0, 0, 1, 1]]
Example 3
Input: kmeans([[1], [2], [3]], 1, 100, 0.000001, 42)
Output: [[[2]], [0, 0, 0]]
Hints
Hint 1
Seed your RNG with `random.Random(seed)` and call `.sample(range(n), k)` to pick the initial centroid indices — this matches the exact initialization the test cases expect.
Hint 2
For the assignment step, squared Euclidean distance is enough for comparisons (no need to take the square root), but you do need the actual Euclidean distance when checking whether centroids moved less than `tol`.
Hint 3
Track both the previous labels and the previous centroids each iteration — stop as soon as labels are identical OR the largest centroid shift is within `tol`, whichever comes first.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
K-means is an iterative two-step process: assign each point to its nearest centroid, then recompute each centroid as the mean of its assigned points. Repeat until stable.
Step-by-step breakdown
Initialization
Use random.Random(seed).sample(range(n), k) to draw k distinct indices and pull out those points as the starting centroids. This is the only initialization strategy the test cases are calibrated against, so the RNG type and call order matter.
Assignment
For each point, compute the squared Euclidean distance to every centroid (squaring is fine here because we only need relative ordering, not actual distances) and pick the index of the minimum. Python's min with a key function breaks ties toward the smaller index, which is the required tie-break rule.
Update
Group points by their new label, then average each coordinate across the group. If a cluster received no points, leave its centroid at its previous position — silently dropping or randomly re-seeding it would change the output.
Convergence
After each update, compute the actual (not squared) Euclidean displacement for every centroid and take the maximum. Stop if that maximum is ≤ tol, or if the label vector is identical to the one from the previous iteration. Either condition guarantees no meaningful progress remains. Also respect the max_iters hard cap.
Why it is correct
- The assignment step strictly minimises total squared distance given fixed centroids.
- The update step strictly minimises total squared distance given fixed assignments.
- Each iteration therefore cannot increase the total within-cluster cost, so the algorithm converges in a finite number of steps.
- Keeping empty-cluster centroids in place prevents crashes and preserves reproducibility.
Complexity
| Time | Space | |
|---|---|---|
| Per iteration | O(n · k · d) | O(n + k · d) |
| Worst case (max_iters) | O(max_iters · n · k · d) | O(n + k · d) |
In practice k-means converges in far fewer than max_iters iterations for well-separated data.
Reference solution
import math
import random
from typing import List, Optional, Tuple
def kmeans(
points: List[List[float]],
k: int,
max_iters: int = 100,
tol: float = 1e-6,
seed: Optional[int] = None,
) -> Tuple[List[List[float]], List[int]]:
n = len(points)
d = len(points[0])
rng = random.Random(seed)
# Initialise centroids from k randomly sampled distinct points
centroids = [list(map(float, points[i])) for i in rng.sample(range(n), k)]
labels = [-1] * n
for _ in range(max_iters):
# --- Assignment step ---
new_labels = []
for point in points:
sq_dists = [
sum((point[j] - centroids[c][j]) ** 2 for j in range(d))
for c in range(k)
]
new_labels.append(min(range(k), key=lambda c: sq_dists[c]))
# --- Update step ---
groups: List[List[List[float]]] = [[] for _ in range(k)]
for point, label in zip(points, new_labels):
groups[label].append(point)
new_centroids = []
for c, group in enumerate(groups):
if group:
new_centroids.append(
[sum(pt[j] for pt in group) / len(group) for j in range(d)]
)
else:
# Empty cluster: keep the centroid in place
new_centroids.append(centroids[c][:])
# --- Convergence checks ---
max_shift = max(
math.sqrt(sum((new_centroids[c][j] - centroids[c][j]) ** 2 for j in range(d)))
for c in range(k)
)
labels_unchanged = new_labels == labels
centroids, labels = new_centroids, new_labels
if labels_unchanged or max_shift <= tol:
break
return centroids, labels