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^51 <= len(points[i]) <= 100, with every vector inpointshaving the exact same lengthd.- All coordinates are finite floating-point numbers (answers within
10^-6tolerance are accepted).
Step-by-step walkthrough
Restate the problem and input shape
We are given
nvectors ind-dimensional space as a list of listspoints, wherepoints[i]storesdfloating-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 intokclusters to minimize the sum of squared Euclidean distances (straight-line geometric distances) from every observation to its assigned centroid (cluster center). Whenk = 1, every observation belongs to the same single group from the start, so no iterative cluster reassignment is needed! We simply want the singled-dimensional vectorc = [c_0, c_1, ..., c_{d-1}]that minimizes:SSE(c) = sum over i=0..n-1 of ||points[i] - c||^2With up to
n = 10^5points andd = 100dimensions (10^7numbers total), reading the input once takesO(n * d)time — and one pass is all we will need.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: evaluatingSSE(points[i])for every input point costsO(n^2 * d)time (10^10operations atn = 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): evaluatesSSEdozens 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.
Key idea: dimensions separate, and the mean minimizes squared error
Write out the squared Euclidean distance between observation
x_iand candidate centerccoordinate 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})^2When summed across all
nobservations,c_0only appears in dimension-0terms,c_1only appears in dimension-1terms, and so on! That lets us minimize each coordinate axis completely independently.Pick a single axis with
nvaluesv_1, v_2, ..., v_n, and letm = (v_1 + ... + v_n) / ndenote their arithmetic mean (ordinary average). Why doesc = mbeat every other valuec? Rewritev_i - cas(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)^2Because
mis the average of thev_ivalues, the signed deviations(v_i - m)above and belowmsum 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)^2is always>= 0and equals0only whenc = m, the arithmetic meanmis the unique global minimizer! (Using calculus, setting the derivative-2 * sum(v_i - c)to0givesn * c = sum(v_i), confirmingc = m.)Code the column-by-column mean safely
To build the centroid, we iterate column by column (
dim = 0 .. d - 1), gather that coordinate across allnpoints, and divide the column total byn: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 centroidOne floating-point detail worth getting right: accumulating
10^5floats with a plaintotal += valloop 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.0rounds straight back to1e16, so(1e16 + 1.0 + -1e16) / 3wrongly yields0.0instead of0.333333...! Python's standardmath.fsumtracks 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 centroidTrace 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], sum6.0,6.0 / 3 = 2.0.dim = 1:coord_values = [4.0, 1.0, 10.0], sum15.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 to84.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 by1->[4.5, -3.0, 0.0], givingSSE = 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 tonum_points = 4, pulling the centroid to[4.0 / 4, 8.0 / 4] = [1.0, 2.0].
- Example 1 (
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 thenobservations once across each of theddimensions to populatecoord_valuesand pass thosennumbers tomath.fsum(O(n)per axis). Since reading alln * dcoordinates already requiresO(n * d)time, this is asymptotically optimal. - Space:
O(n + d)auxiliary memory, becausecoord_valuesholds one column ofnfloats at a time (reused across axes) andcentroidstores thedoutput coordinates. (Streaming rows reduces auxiliary space toO(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 theList[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.0at[0.0, 0.0]). - Duplicate or origin vectors: Repeated vectors (including
[0.0, 0.0]) each incrementnum_points, weighting the centroid toward denser regions. - Extreme cancelling magnitudes (
[[1e16], [1.0], [-1e16]]): Plainsum()evaluates1e16 + 1.0as1e16and returns[0.0], whereasmath.fsumpreserves the1.0and returns[1/3]. - Empty input (
points = []): Outsiden >= 1, raisingValueErrorfails explicitly instead of crashing withZeroDivisionErrororIndexError.
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 continuousR^dspace. - Averaging across a point's coordinates (
sum(point) / d) instead of across observations (sum(column) / n): Mixing up rows and columns outputsnnumbers instead of ad-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
ndarrayinstead of a Pythonlist: Call.tolist()if NumPy is used internally so type checks expectinglistsucceed.
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 preservingmath.fsumaccuracy. - Vectorized NumPy mean:
np.asarray(points, dtype=np.float64).mean(axis=0).tolist()executes compiled C loops and is substantially faster on10^7floats, 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 fromO(n * d)toO(d)by reading points in small chunks and maintaining onlydrunning totals plus a single integer countercount. To guard against floating-point drift across billions of records without buffering full columns, sum each chunk withmath.fsumor 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 thoseO(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 ofR^dstill separates by axis, turning each coordinatec_jinto the 1-D median solvable inO(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) overR^ddefines the geometric median, where axes couple together and no closed-form formula exists — you solve it iteratively with Weiszfeld's algorithm (repeatedly updatingcto an inverse-distance-weighted average of the points using weights1 / ||x_i - c||_2, handlingc == x_iexplicitly). Third, constrainingcto be an existing dataset point (the medoid) requiresO(n^2 * d)exact pairwise evaluation for general L1/Euclidean distances (or random-sample approximation at largen), though for squared Euclidean distance you can pick the input point closest to the already-computed mean[c_0, ..., c_{d-1}]inO(n * d)time becausesum_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 at0) and the currentd-dimensional mean vectorc = [0.0] * d. Upon receiving a new vectorx, incrementt += 1and update each coordinatejin place via Welford's incremental mean update:c[j] += (x[j] - c[j]) / t. Each arrival takesO(d)time andO(d)total space, avoids overflow from giant running sums, and if recent observations should outweigh stale history you can replace1 / twith a constant step sizealpha(an exponential moving average, which decays older weights exponentially).
Follow-up questions
- What happens to time and memory complexity when the dataset has too many points to fit into main memory at once?
- 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?
- How can you maintain the exact centroid incrementally in a streaming setting where points arrive one at a time?
Similar questions
- Decode Delimited and Ambiguous Morse Strings
- Express Soft K-Means Assignment as a Single Linear Layer
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance