Single-Cluster K-Means Centroid

Easy · Coding & Algorithms · Machine Learning Engineer · Onsite

Problem Statement

When k-means clustering is run with a single cluster (k = 1), every observation belongs to one group and the objective reduces to finding a single center vector c in d-dimensional space that minimizes the total squared Euclidean distance across all n observations:

sum over i = 0 .. n - 1 of  sum over j = 0 .. d - 1 of  (points[i][j] - c[j])^2

Given points, a non-empty list of n vectors where points[i] contains the d floating-point coordinates of observation i, implement find_one_cluster_centroid(points) to return the optimal d-dimensional center vector as a List[float].

Examples

Example 1

Input:

points = [[-2.0, 4.0], [1.0, 1.0], [7.0, 10.0]]

Output:

[2.0, 5.0]

Explanation: Averaging coordinate 0 across the three vectors gives (-2.0 + 1.0 + 7.0) / 3 = 2.0, and averaging coordinate 1 gives (4.0 + 1.0 + 10.0) / 3 = 5.0. No other point in 2-dimensional space yields a smaller sum of squared Euclidean distances than [2.0, 5.0].

Example 2

Input:

points = [[4.5, -3.0, 0.0]]

Output:

[4.5, -3.0, 0.0]

Explanation: With only one vector in 3-dimensional space, placing the center directly on [4.5, -3.0, 0.0] achieves a total squared distance of 0.0.

Constraints

  • 1 <= len(points) <= 10^5
  • 1 <= len(points[i]) <= 100, with every vector in points having the exact same length d.
  • All coordinates are finite floating-point numbers (answers within 10^-6 tolerance are accepted).

Step-by-step walkthrough

  1. Restate the problem and input shape

    We are given n vectors in d-dimensional space as a list of lists points, where points[i] stores d floating-point coordinates:

    points (n = 3 points, d = 2 dimensions):
                  dim 0   dim 1
      point 0 -> [ -2.0,   4.0 ]
      point 1 -> [  1.0,   1.0 ]
      point 2 -> [  7.0,  10.0 ]
    

    In general k-means clustering, observations are grouped into k clusters to minimize the sum of squared Euclidean distances (straight-line geometric distances) from every observation to its assigned centroid (cluster center). When k = 1, every observation belongs to the same single group from the start, so no iterative cluster reassignment is needed! We simply want the single d-dimensional vector c = [c_0, c_1, ..., c_{d-1}] that minimizes:

    SSE(c) = sum over i=0..n-1 of ||points[i] - c||^2
    

    With up to n = 10^5 points and d = 100 dimensions (10^7 numbers total), reading the input once takes O(n * d) time — and one pass is all we will need.

  2. Brute force search, and why algebra beats it

    If we treated SSE(c) as a black-box score without looking inside the formula: - Testing only input points: evaluating SSE(points[i]) for every input point costs O(n^2 * d) time (10^10 operations at n = 10^5 — far too slow!) and usually gives the wrong answer because the true optimum typically lies in open space between points rather than on top of one. - Iterative numerical optimization (gradient descent or ternary search): evaluates SSE dozens of times to creep toward the minimum, costing tens of passes and stopping with small approximation errors.

    Expanding the squared distance algebraically reveals the exact global minimizer in one clean pass.

  3. Key idea: dimensions separate, and the mean minimizes squared error

    Write out the squared Euclidean distance between observation x_i and candidate center c coordinate by coordinate (the square root in Euclidean distance cancels cleanly when squared!):

    ||x_i - c||^2 = (x_i,0 - c_0)^2 + (x_i,1 - c_1)^2 + ... + (x_i,d-1 - c_{d-1})^2
    

    When summed across all n observations, c_0 only appears in dimension-0 terms, c_1 only appears in dimension-1 terms, and so on! That lets us minimize each coordinate axis completely independently.

    Pick a single axis with n values v_1, v_2, ..., v_n, and let m = (v_1 + ... + v_n) / n denote their arithmetic mean (ordinary average). Why does c = m beat every other value c? Rewrite v_i - c as (v_i - m) + (m - c) and expand the square:

    sum((v_i - c)^2) = sum((v_i - m)^2) + 2*(m - c)*sum(v_i - m) + n*(m - c)^2
    

    Because m is the average of the v_i values, the signed deviations (v_i - m) above and below m sum to exact zero (sum(v_i - m) = 0), eliminating the cross term:

    sum((v_i - c)^2) = sum((v_i - m)^2) + n * (m - c)^2
                       |--------------|   |------------|
                        fixed spread       >= 0 penalty!
    

    Since n * (m - c)^2 is always >= 0 and equals 0 only when c = m, the arithmetic mean m is the unique global minimizer! (Using calculus, setting the derivative -2 * sum(v_i - c) to 0 gives n * c = sum(v_i), confirming c = m.)

  4. Code the column-by-column mean safely

    To build the centroid, we iterate column by column (dim = 0 .. d - 1), gather that coordinate across all n points, and divide the column total by n:

               dim 0    dim 1
    point 0: [ -2.0,     4.0 ]
    point 1: [  1.0,     1.0 ]
    point 2: [  7.0,    10.0 ]
               -----    -----
    col sum:    6.0     15.0
    divide /3: [2.0,     5.0]  <-- optimal centroid
    

    One floating-point detail worth getting right: accumulating 10^5 floats with a plain total += val loop can suffer catastrophic cancellation (where huge positive and negative numbers swallow small numbers due to finite 64-bit float precision). For example, in standard IEEE-754 arithmetic, 1e16 + 1.0 rounds straight back to 1e16, so (1e16 + 1.0 + -1e16) / 3 wrongly yields 0.0 instead of 0.333333...! Python's standard math.fsum tracks exact partial sums internally and returns the accurately rounded sum in one call.

    from typing import List
    import math
    
    
    def find_one_cluster_centroid(points: List[List[float]]) -> List[float]:
        # Guard against empty input to avoid dividing by zero or indexing points[0].
        if not points:
            raise ValueError("points must contain at least one point")
    
        num_points = len(points)
        num_dims = len(points[0])
    
        # centroid: list of d floats holding the optimal mean coordinate per dimension,
        # e.g. [2.0, 5.0] for [[-2.0, 4.0], [1.0, 1.0], [7.0, 10.0]].
        centroid: List[float] = []
    
        # Squared Euclidean distance separates across dimensions, so we minimize
        # each coordinate's sum of squares independently via its arithmetic mean.
        for dim in range(num_dims):
            # coord_values: all n coordinates in dimension 'dim', e.g. [-2.0, 1.0, 7.0]
            coord_values: List[float] = []
            for point in points:
                coord_values.append(point[dim])
    
            # math.fsum tracks exact floating-point partial sums so huge cancelling
            # values (such as 1e16 + 1.0 - 1e16) do not lose small contributions.
            dim_mean = math.fsum(coord_values) / num_points
            centroid.append(dim_mean)
    
        return centroid
    
  5. Trace the examples and boundary cases

    Let's walk through our two examples and repeated-origin edge cases:

    • Example 1 ([[-2.0, 4.0], [1.0, 1.0], [7.0, 10.0]]): num_points = 3, num_dims = 2.
      • dim = 0: coord_values = [-2.0, 1.0, 7.0], sum 6.0, 6.0 / 3 = 2.0.
      • dim = 1: coord_values = [4.0, 1.0, 10.0], sum 15.0, 15.0 / 3 = 5.0.
      • Returns [2.0, 5.0]. Total squared error is (16 + 1) + (1 + 16) + (25 + 25) = 84.0; shifting the center by any [dx, dy] raises the error to 84.0 + 3 * (dx^2 + dy^2).
    • Example 2 ([[4.5, -3.0, 0.0]]): num_points = 1, num_dims = 3. Each column has a single entry divided by 1 -> [4.5, -3.0, 0.0], giving SSE = 0.0.
    • Repeated origin points ([[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [4.0, 8.0]]): Zero coordinates still represent genuine observations and contribute to num_points = 4, pulling the centroid to [4.0 / 4, 8.0 / 4] = [1.0, 2.0].
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import math
    
    
    def find_one_cluster_centroid(points: List[List[float]]) -> List[float]:
        # Guard against empty input to avoid dividing by zero or indexing points[0].
        if not points:
            raise ValueError("points must contain at least one point")
    
        num_points = len(points)
        num_dims = len(points[0])
    
        # centroid: list of d floats holding the optimal mean coordinate per dimension,
        # e.g. [2.0, 5.0] for [[-2.0, 4.0], [1.0, 1.0], [7.0, 10.0]].
        centroid: List[float] = []
    
        # Squared Euclidean distance separates across dimensions, so we minimize
        # each coordinate's sum of squares independently via its arithmetic mean.
        for dim in range(num_dims):
            # coord_values: all n coordinates in dimension 'dim', e.g. [-2.0, 1.0, 7.0]
            coord_values: List[float] = []
            for point in points:
                coord_values.append(point[dim])
    
            # math.fsum tracks exact floating-point partial sums so huge cancelling
            # values (such as 1e16 + 1.0 - 1e16) do not lose small contributions.
            dim_mean = math.fsum(coord_values) / num_points
            centroid.append(dim_mean)
    
        return centroid
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine fastening n pins onto a flat board and attaching an ideal rubber band from every pin to one movable ring. Because a stretched spring's potential energy grows with the square of its length, the ring slides until the total squared Euclidean distance (straight-line distance between vectors) reaches its minimum — settling right at the pins' center of mass, which is the coordinate-wise arithmetic mean (ordinary average)! When k-means is run with k = 1, every point belongs to the single cluster permanently, so finding the optimal centroid (cluster center) needs zero iterative reassignment steps: because squared Euclidean distance expands into (x_i - c_x)^2 + (y_i - c_y)^2 + ... with no cross terms between axes, we simply average each coordinate axis on its own.

A naive implementation either checks every input point as a candidate center in O(n^2 * d) time — requiring 10^10 operations at n = 10^5 and failing whenever the true center lies in empty space between points — or runs iterative gradient descent that takes dozens of passes for an approximate result. Even when computing the average directly, summing 10^5 floats with total += value risks catastrophic cancellation (losing small contributions when huge positive and negative numbers cancel in 64-bit floating point), which Python's math.fsum prevents cleanly.

Trace Example 1 (points = [[-2.0, 4.0], [1.0, 1.0], [7.0, 10.0]], n = 3 points, d = 2 dimensions): 1. Gather axis 0 (x-coordinates): [-2.0, 1.0, 7.0] -> sum is 6.0, divided by 3 gives 2.0. 2. Gather axis 1 (y-coordinates): [4.0, 1.0, 10.0] -> sum is 15.0, divided by 3 gives 5.0. 3. Return [2.0, 5.0], achieving the minimum possible total squared distance (16 + 1) + (1 + 16) + (25 + 25) = 84.0.

Complexity

  • Time: O(n * d), because we visit each of the n observations once across each of the d dimensions to populate coord_values and pass those n numbers to math.fsum (O(n) per axis). Since reading all n * d coordinates already requires O(n * d) time, this is asymptotically optimal.
  • Space: O(n + d) auxiliary memory, because coord_values holds one column of n floats at a time (reused across axes) and centroid stores the d output coordinates. (Streaming rows reduces auxiliary space to O(d), as covered in the first follow-up.)

Edge cases

  • Single observation (n = 1, Example 2 [[4.5, -3.0, 0.0]]): Each axis averages a 1-element list, returning a copy of that exact vector with zero squared error.
  • One-dimensional vectors (d = 1, e.g., [[1.0], [2.0], [9.0]]): Returns a 1-element list [4.0] rather than a bare scalar float, preserving the List[float] return type.
  • Optimum outside the input set: For triangle vertices [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]], the true centroid [1/3, 1/3] (SSE = 4/3) strictly beats every input vertex (SSE = 2.0 at [0.0, 0.0]).
  • Duplicate or origin vectors: Repeated vectors (including [0.0, 0.0]) each increment num_points, weighting the centroid toward denser regions.
  • Extreme cancelling magnitudes ([[1e16], [1.0], [-1e16]]): Plain sum() evaluates 1e16 + 1.0 as 1e16 and returns [0.0], whereas math.fsum preserves the 1.0 and returns [1/3].
  • Empty input (points = []): Outside n >= 1, raising ValueError fails explicitly instead of crashing with ZeroDivisionError or IndexError.

Common mistakes

  • Restricting the answer to an input point (the medoid): A medoid forces the center to be one of the dataset's points, whereas the k-means centroid can sit anywhere in continuous R^d space.
  • Averaging across a point's coordinates (sum(point) / d) instead of across observations (sum(column) / n): Mixing up rows and columns outputs n numbers instead of a d-dimensional vector.
  • Computing the coordinate-wise median instead of the mean: The median minimizes absolute (L1) deviations (|x - c|), not squared (L2) deviations ((x - c)^2).
  • Returning a NumPy ndarray instead of a Python list: Call .tolist() if NumPy is used internally so type checks expecting list succeed.

Alternative approaches

  • Column unpacking with zip(*points): [math.fsum(col) / len(points) for col in zip(*points)] transposes rows into columns concisely at C speed while preserving math.fsum accuracy.
  • Vectorized NumPy mean: np.asarray(points, dtype=np.float64).mean(axis=0).tolist() executes compiled C loops and is substantially faster on 10^7 floats, using pairwise summation.

Follow-up questions

  • What happens to time and memory complexity when the dataset has too many points to fit into main memory at once? Total work remains O(n * d) (now bounded by sequential disk or network throughput rather than CPU), while RAM usage drops from O(n * d) to O(d) by reading points in small chunks and maintaining only d running totals plus a single integer counter count. To guard against floating-point drift across billions of records without buffering full columns, sum each chunk with math.fsum or maintain Kahan compensated summation (storing one tiny running rounding-error variable per axis). Across a cluster of machines, this maps directly to MapReduce (each worker emits (partial_sums, partial_count) for its partition, and a reducer sums those O(d) summaries).
  • How would the algorithm change if you minimized total L1 absolute error, unsquared Euclidean distance (the geometric median), or constrained the center to be one of the input points? Those three objectives behave quite differently! First, minimizing coordinate-wise absolute differences (Manhattan / L1 distance, sum_i sum_j |x_ij - c_j|) over all of R^d still separates by axis, turning each coordinate c_j into the 1-D median solvable in O(n * d) expected time via quickselect (O(n * log(n) * d) by sorting). Second, minimizing unsquared straight-line Euclidean distances (sum_i ||x_i - c||_2) over R^d defines the geometric median, where axes couple together and no closed-form formula exists — you solve it iteratively with Weiszfeld's algorithm (repeatedly updating c to an inverse-distance-weighted average of the points using weights 1 / ||x_i - c||_2, handling c == x_i explicitly). Third, constraining c to be an existing dataset point (the medoid) requires O(n^2 * d) exact pairwise evaluation for general L1/Euclidean distances (or random-sample approximation at large n), though for squared Euclidean distance you can pick the input point closest to the already-computed mean [c_0, ..., c_{d-1}] in O(n * d) time because sum_i ||x_i - p||^2 = sum_i ||x_i - mean||^2 + n * ||mean - p||^2!
  • How can you maintain the exact centroid incrementally in a streaming setting where points arrive one at a time? Store only the seen count t (starting at 0) and the current d-dimensional mean vector c = [0.0] * d. Upon receiving a new vector x, increment t += 1 and update each coordinate j in place via Welford's incremental mean update: c[j] += (x[j] - c[j]) / t. Each arrival takes O(d) time and O(d) total space, avoids overflow from giant running sums, and if recent observations should outweigh stale history you can replace 1 / t with a constant step size alpha (an exponential moving average, which decays older weights exponentially).

Follow-up questions

Similar questions

More Sealth interview questions

All 3 Sealth questions →