K-Means Iteration

HardMachine LearningMath

Description

Given a list of points and a list of current centroids, perform one full k-means iteration: assign each point to its nearest centroid by Euclidean distance (ties toward the lower index), then move each centroid to the coordinate-wise mean of the points assigned to it. A centroid with no assigned points keeps its current position. Return the new centroids, each coordinate rounded to 4 decimal places.

Examples

Input:[[1,1],[2,2],[8,8],[9,9]], [[0,0],[10,10]]
Output:[[1.5,1.5],[8.5,8.5]]
Explanation:

Every point joins its nearest centroid, then each centroid moves to the coordinate-wise mean of its members. Each centroid lands on the average position of the points that chose it.

Input:[[1,1],[1,2],[10,10]], [[0,0],[9,9]]
Output:[[1,1.5],[10,10]]
Explanation:

Every point joins its nearest centroid, then each centroid moves to the coordinate-wise mean of its members. Each centroid lands on the average position of the points that chose it.

Input:[[1,1],[2,2]], [[0,0],[9,9]]
Output:[[1.5,1.5],[9,9]]
Explanation:

Every point joins its nearest centroid, then each centroid moves to the coordinate-wise mean of its members. One centroid receives no points this round, so it stays exactly where it was.

Constraints

  • 1 ≤ points, centroids ≤ 10³
  • All vectors share the same dimension

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.