Problem Description
A delivery company wants to build a new service center such that the sum of the Euclidean distances from the center to all customer locations is minimized. Given an array of positions [[x₁, y₁], [x₂, y₂], ..., [xn, yn]], return the minimum possible sum of distances when the service center is optimally placed.
Key Insights
- This is a geometric median problem where the goal is to minimize the sum of Euclidean distances.
- Unlike the 1D case, the optimal point in 2D (known as the geometric median) is not simply the average or median of the coordinates.
- Weiszfeld's algorithm is an iterative procedure used to approximate the geometric median.
- With at most 50 points, an iterative approach with a convergence threshold (e.g., 10⁻⁵) is efficient.
- Special care is needed to avoid division by zero when the current guess exactly matches a customer’s position.
Space and Time Complexity
Time Complexity: O(n * iterations), where n is the number of points and iterations is the number of update steps needed for convergence.
Space Complexity: O(n) for storing the positions.
Solution
We use Weiszfeld's algorithm to approximate the geometric median. The process starts with an initial guess (typically the centroid), and iteratively updates the guess using a weighted average of the customer positions. The weight for each point is the inverse of its distance from the current guess. The iterations stop when the movement between iterations is less than the threshold (e.g., 10⁻⁵). Finally, the sum of Euclidean distances is computed with the converged point.