Skip to content
RED SAGSkills

One Step of K-Means

Run a single iteration of k-means clustering. points is a list of d-dimensional points and centroids the current k centroids (same dimension).

**Assign:** each point goes to the centroid with the smallest squared Euclidean distance; on a tie, the centroid with the lower index wins.

**Update:** each centroid becomes the mean of its assigned points, coordinate by coordinate. A centroid with no points stays where it is.

Return { assignments, centroids }, where assignments[i] is the centroid index of point i and every new centroid coordinate is rounded to 4 decimals (Math.round(x * 10000) / 10000).

Example 1

Input: points = [[1,1],[2,1],[8,9],[9,8]], centroids = [[0,0],[10,10]]
Output: {"assignments":[0,0,1,1],"centroids":[[1.5,1],[8.5,8.5]]}
Explanation: The first two points join centroid 0, the last two centroid 1.

Example 2

Input: points = [[0],[10]], centroids = [[5],[5]]
Output: {"assignments":[0,0],"centroids":[[5],[5]]}

Constraints

  • 1 <= points.length <= 10^4
  • 1 <= k <= 50
  • 1 <= d <= 20
  • -10^4 <= coordinates <= 10^4
Hint 1

Use squared distance; no need for Math.sqrt.

Hint 2

Keep a running sum and count per centroid during assignment.

Good practice for: Data Scientist, Machine Learning Engineer, AI Engineer (LLM & Generative AI), MLOps Engineer, Data Engineer, Backend Developer

Run checks your code on 3 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.