Best Position for a Service Centre - Problem

A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum.

Given an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers.

In other words, you need to choose the position of the service center [xcentre, ycentre] such that the sum of distances √((xi-xcentre)² + (yi-ycentre)²) for all customers is minimized.

Answers within 10⁻⁵ of the actual value will be accepted.

Input & Output

Example 1 — Square Formation
$ Input: positions = [[0,1],[1,0],[1,2],[2,1]]
Output: 4.00000
💡 Note: Customers form a square pattern. The optimal service center is at (1,1) which gives equal distances √2 to each corner, total = 4×√2 ≈ 5.66. However, the actual optimal position minimizes this further to approximately 4.0.
Example 2 — Linear Arrangement
$ Input: positions = [[1,1],[3,3]]
Output: 2.82843
💡 Note: Two customers at (1,1) and (3,3). Optimal center is at midpoint (2,2), giving distances √2 + √2 = 2√2 ≈ 2.828 to both customers.
Example 3 — Single Customer
$ Input: positions = [[1,1]]
Output: 0.00000
💡 Note: Only one customer at (1,1). The service center should be placed at the same location, giving total distance = 0.

Constraints

  • 1 ≤ positions.length ≤ 50
  • positions[i].length == 2
  • 0 ≤ positions[i][0], positions[i][1] ≤ 100

Visualization

Tap to expand
Best Position for a Service Centre Geometric Median Problem - Gradient Descent Optimization INPUT x y C1 C2 C3 C4 positions = [ [0,1],[1,0],[1,2],[2,1] ] = Customer Location Find optimal center position ALGORITHM STEPS 1 Initialize Center Start at centroid: (1, 1) 2 Compute Gradient Sum of unit vectors to points 3 Update Position Move against gradient 4 Repeat Until Converge Step size decreases Convergence Path OK Center converges to (1,1) FINAL RESULT OPT Distance Sum: d1 = sqrt(1) = 1.0 d2 = sqrt(1) = 1.0 d3 = sqrt(1) = 1.0 d4 = sqrt(1) = 1.0 Output: 4.00000 Key Insight: The optimal service center is the Geometric Median, which minimizes the sum of Euclidean distances. Unlike the arithmetic mean (centroid), the geometric median has no closed-form solution and requires iterative optimization. Gradient Descent converges by moving opposite to the sum of unit direction vectors. TutorialsPoint - Best Position for a Service Centre | Gradient Descent Optimization
Asked in
Google 15 Amazon 12 Microsoft 8
18.5K Views
Medium Frequency
~35 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen