KatInterview

K-Means Clustering: Assignment, Update, and Convergence

Arrays & HashingAuto-graded · 15 test cases
MediumAuto-gradedArrays & Hashingclusteringiterative-algorithmsnumerical

Last 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:

  1. Centroids — a list of k points (each a list of floats) representing the final cluster centers.
  2. 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, where n = len(points).
  • All points share the same dimension d >= 1.
  • 1 <= max_iters <= 10_000.
  • 0 < tol <= 1.0.
  • seed is either None or a non-negative integer; results must be fully reproducible when seed is provided.
  • Point coordinates are finite floats.
  • k = 1 and k = n are 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.