Quick Overview

Minimize one-dimensional squared-distance clustering cost with mean-based interval costs, prefix sums, and partition dynamic programming; compare k-means.

Partition One-Dimensional Points to Minimize Squared Distance

Company: LinkedIn

Role: Machine Learning Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Technical Screen

Given n integer positions on a line and k centers, assign each position to a center to minimize the total squared distance. Centers may be any real values. Return the minimum cost; dividing by n gives the minimum mean squared distance. This is a squared-distance variant of one-dimensional facility placement. Explain why a cluster center is its mean rather than its median, and give an exact dynamic-programming solution using prefix sums. Also discuss a simpler approximate clustering method. ### Constraints & Assumptions Assume nonempty input and `1 <= k <= n`, with nonempty clusters. The implementation returns an exact rational cost for integer positions; centers remain unrestricted real values. Restricting centers to integers would change the cluster cost. ### Clarifying Questions to Ask - Is the objective total squared error or its mean over all points? - Can centers lie at noninteger locations? ```hint Expand the square For a fixed consecutive group, its optimal cost can be expressed using the sum of values and the sum of squared values. ``` ### What a Strong Answer Covers - A proof that the mean minimizes a cluster's squared error. - Sorted contiguous clusters and constant-time interval cost from prefix statistics. - The partition DP, feasible bounds, and complexity. - K-means as an initialization-sensitive approximate alternative. ### Follow-up Questions - Why does the median solve absolute distance instead? - How would you reconstruct center positions from the optimal partition?

Overview: Minimize one-dimensional squared-distance clustering cost with mean-based interval costs, prefix sums, and partition dynamic programming; compare k-means.

Read the full LinkedIn Machine Learning Engineer interview experience this question came from

Given an array of integer positions on a line and an integer `k`, assign every position to one of `k` centers so that the sum of squared distances to the assigned centers is as small as possible. Centers can be any real numbers, and every cluster must contain at least one position. Positions may repeat and arrive in any order. Return the minimum total squared error as `(numerator, denominator)` using canonical decimal strings. The fraction must be reduced and its denominator positive. Return `("0", "1")` for zero.

Constraints

  • 1 ≤ k ≤ n ≤ 2^31 − 1, where n is the number of positions.
  • Each position is an integer from −(2^53 − 1) through 2^53 − 1, inclusive.

Examples

Input: ([0, 1], 1)

Expected Output: ('1', '2')

Explanation: The unrestricted center is 0.5, giving total squared error 0.5.

Input: ([8, 1, 9, 0], 2)

Expected Output: ('1', '1')

Explanation: The two adjacent pairs each contribute one half.

Hints

  1. The objective sums the squared distances for all positions. A center may lie between integer coordinates.

Minimum Squared Distance to K Centers

hardLinkedInMachine Learning Engineer

Given an array of integer positions on a line and an integer k, assign every position to one of k centers so that the sum of squared distances to the assigned centers is as small as possible. Centers can be any real numbers, and every cluster must contain at least one position. Positions may repeat and arrive in any order.

Return the minimum total squared error as (numerator, denominator) using canonical decimal strings. The fraction must be reduced and its denominator positive. Return ("0", "1") for zero.

Examples

Example 1
Input
([0, 1], 1)
Output
('1', '2')
Notes
The unrestricted center is 0.5, giving total squared error 0.5.
Example 2
Input
([8, 1, 9, 0], 2)
Output
('1', '1')
Notes
The two adjacent pairs each contribute one half.

Constraints

  • •1 ≤ k ≤ n ≤ 2^31 − 1, where n is the number of positions.
  • •Each position is an integer from −(2^53 − 1) through 2^53 − 1, inclusive.

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def minimum_squared_partition_cost(positions: list[int], k: int) -> tuple[str, str]:
Sample call
minimum_squared_partition_cost([0, 1], 1)
Language
Case 1
Input
([0, 1], 1)
Expected
('1', '2')
Case 2
Input
([8, 1, 9, 0], 2)
Expected
('1', '1')

Browse More Questions

Show the approach

Approach

For a cluster of m points with sum S and squared sum Q, expanding the sum of squared deviations shows that its minimum is Q − S²/m, achieved at the mean. In sorted order, assignments may be made contiguous. With two ordered centers, exchanging a crossing pair cannot increase cost. Empty groups caused by ties can be resolved by contiguous splitting without increasing the optimum.

Store prefix sums and prefix squared sums so each interval contributes one exact fraction. Let dp[g,e] be the best cost to partition the first e sorted positions into g nonempty clusters. Try each feasible last split s and take the minimum of dp[g−1,s] plus the cost for indices s through e−1.

The squared-error interval cost has the Monge property. For ordered disjoint blocks A, B and C, the extra cost from adding A to B is the product of their counts divided by the combined count, times the squared distance of their means. Adding A to B together with C can only increase that extra cost, since the right block grows and its mean moves no closer to A. This proves the quadrangle inequality and makes the earliest optimal split nondecreasing in e. Compute the middle end of a range first and recurse on the two sides with narrower split ranges.

Compare exact fractions. An equivalent implementation scales all interval costs by a common multiple of the feasible cluster lengths, performs integer comparisons, and reduces the final fraction. Iterative k-means is a practical approximate alternative whose result depends on initialization.

Time complexity:
O(n log n + kn log n) arithmetic operations, plus the cost of exact large-integer arithmetic.
Space complexity:
O(n) stored arithmetic values excluding input and output. Each value may use multiple machine words.