KatInterview

Seeded Two-Round K-Means with Spread-Out Starting Centers

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingsimulationclusteringrandomized-sampling

Last updated

Simulate k-means++ seeding with a fixed RNG protocol, then run two assign/update rounds and report clusters, centroids and final squared error.

You are given a list of points in d-dimensional space and a number of clusters k. Simulate a short k-means run: pick starting centers with a distance-weighted random rule, then run exactly two assign-and-update rounds, then report the squared error.

The random choices must follow the protocol below exactly, so every correct solution produces the same output for the same seed.

Seeding the centers

Create a generator with Python's standard random.Random(seed). Call rng.randrange(...) and rng.random() only as described here, in this order.

  1. First center: call rng.randrange(n), where n is the number of points, and take the point at that index.
  2. Each further center, until k centers are chosen:
    • For every point, compute its weight: the smallest squared Euclidean distance from that point to any center chosen so far.
    • Let total be the sum of all weights.
    • If total > 0, draw threshold = rng.random() * total. Walk through the points in index order, keeping a running sum of weights. Choose the first index where threshold < running_sum. If no index qualifies because of rounding, choose the last index.
    • If total == 0, do not call the generator. Call an index "used" if its point has the same coordinates as any center chosen so far. Choose the smallest index that is not used. If every index is used, choose index 0.
    • Append a copy of the chosen point as the next center.

Record the list of chosen centers, in the order chosen, as the sampled centers.

The two rounds

Repeat the following twice, starting from the sampled centers:

  1. Assign: send each point to the center with the smallest squared Euclidean distance. If two centers are tied, pick the one with the lower index. Within each cluster, keep the points in their original input order.
  2. Update: replace each center with the coordinate-wise mean of its cluster. If a cluster is empty, keep that center unchanged.

After each round, record the clusters (a list of k lists of points) and the centers after the update.

Final error

After the second round, compute the sum, over all points, of the squared distance to the nearest of the final centers.

Return value

Return a dictionary with these keys:

  • "sampledCenters": list of k points, the centers from seeding.
  • "iterations": list of two dictionaries, one per round, each with
    • "clusters": list of k lists of points, indexed by center, from that round's assign step;
    • "centroids": list of k points, the centers after that round's update step.
  • "sse": the final squared error as a number.

Constraints

  • 1 <= k <= len(points)
  • points is non-empty, and every point has the same dimension d >= 1.
  • Coordinates are finite numbers.
  • Points may repeat.
  • Use squared distances throughout, computed by summing over coordinates in order. Do not take square roots.
  • Compare results as exact values from the described procedure. Do not use another random source or a different order of random calls.

Examples

Example 1

Input: run_seeded_kmeans_two_rounds([[0, 0], [0, 2], [2, 0], [2, 2], [8, 8], [8, 10], [10, 8], [10, 10]], 2, 42)

Output: {'sampledCenters': [[0, 2], [2, 2]], 'iterations': [{'clusters': [[[0, 0], [0, 2]], [[2, 0], [2, 2], [8, 8], [8, 10], [10, 8], [10, 10]]], 'centroids': [[0, 1], [6.666666666666667, 6.333333333333333]]}, {'clusters': [[[0, 0], [0, 2], [2, 0], [2, 2]], [[8, 8], [8, 10], [10, 8], [10, 10]]], 'centroids': [[1, 1], [9, 9]]}], 'sse': 16}

Hints

Hint 1

Keep the random calls exactly as specified: one randrange for the first center, then one random() per further center, and none at all when the total weight is zero.

Hint 2

For the weighted pick, build the running sum of weights and take the first index where the threshold is strictly less than that sum. Python's min over a range of indices already breaks distance ties toward the lower index.

Hint 3

Write one helper for squared distance and reuse it for seeding, assignment and the final error. Remember that an empty cluster keeps its previous center.