One k-means iteration

A free medium coding practice problem from ml. Solve it in JavaScript, TypeScript or Python and check your solution against fresh hidden tests — edge cases and random inputs — as often as you like.

Difficulty
Medium
Type
Function
Topic
Ml
Languages
JavaScript, TypeScript or Python

Problem

Run ONE iteration of k-means on 2-D points with non-negative integer coordinates. points and centroids are lists of [x, y] (at least one centroid).
1. Assign each point to the centroid with the smallest SQUARED Euclidean distance; on a tie, the centroid with the lower index.
2. Move each centroid to the mean of its assigned points, each coordinate rounded DOWN (floor(sumX / count), floor(sumY / count)); a centroid with no points stays where it is.

Return [assignments, newCentroids] where assignments[i] is the centroid index of points[i]. Coordinates ≤ 10 000, up to 10 000 points and 50 centroids.

Function signature

// JavaScript
function kmeansStep(points, centroids)

// TypeScript
function kmeansStep(points: any, centroids: any): any

// Python
def kmeans_step(points, centroids):

Examples

  1. kmeansStep([[0,0],[1,1],[9,9],[10,10]], [[0,0],[10,10]]) → [[0,0,1,1],[[0,0],[9,9]]]
  2. kmeansStep([[2,0],[0,0]], [[1,0],[1,0],[50,50]]) → [[0,0],[[1,0],[1,0],[50,50]]]

How checking works

Run your code against the examples above, then submit a check: it runs on the server against hidden tests built fresh each time, including edge cases and random inputs. Practice is untimed and never affects a verified score; when you are ready, take a graded coding challenge to earn a badge.

More practice problems

Next steps