Best Position for a Service Centre - Problem
Problem Overview: A delivery company is expanding to a new city and needs to strategically place their service center. They have the exact coordinates of all their customers on a 2D map and want to minimize the total travel distance.
Your Task: Given an array
The Euclidean distance between two points
Note: This is a classic geometric optimization problem known as the Geometric Median or Fermat Point problem. Answers within
Your Task: Given an array
positions where positions[i] = [xi, yi] represents the coordinates of the ith customer, find the optimal location [xcentre, ycentre] for the service center that minimizes the sum of Euclidean distances to all customers.The Euclidean distance between two points
(x1, y1) and (x2, y2) is √[(x1-x2)² + (y1-y2)²].Note: This is a classic geometric optimization problem known as the Geometric Median or Fermat Point problem. Answers within
10⁻⁵ of the actual value will be accepted. Input & Output
example_1.py — Python
$
Input:
positions = [[0,1],[1,0],[1,2],[2,1]]
›
Output:
4.00000
💡 Note:
The service center should be placed at (1,1). Total distance = √[(1-0)² + (1-1)²] + √[(1-1)² + (1-0)²] + √[(1-1)² + (1-2)²] + √[(1-2)² + (1-1)²] = 1 + 1 + 1 + 1 = 4.00000
example_2.py — Python
$
Input:
positions = [[1,1],[3,3]]
›
Output:
2.82843
💡 Note:
The optimal center is at (2,2). Total distance = √[(2-1)² + (2-1)²] + √[(2-3)² + (2-3)²] = √2 + √2 = 2√2 ≈ 2.82843
example_3.py — Python
$
Input:
positions = [[1,1]]
›
Output:
0.00000
💡 Note:
With only one customer, the optimal service center location is at the customer's position (1,1), resulting in zero total distance.
Visualization
Tap to expand
Understanding the Visualization
1
Plot Customers
Mark all customer locations on a 2D map
2
Search Strategy
Choose between grid search (test every point) or smart optimization
3
Calculate Distances
For each candidate location, sum up distances to all customers
4
Find Minimum
The location with smallest total distance is optimal
Key Takeaway
🎯 Key Insight: The geometric median minimizes total Euclidean distances and can be found efficiently using mathematical optimization techniques rather than brute force search.
Time & Space Complexity
Time Complexity
O(log³(1/ε) × n)
Nested ternary searches with precision ε, each evaluation costs O(n)
⚡ Linearithmic
Space Complexity
O(1)
Only need variables for search bounds and current best
✓ Linear Space
Constraints
- 1 ≤ positions.length ≤ 50
- positions[i].length == 2
- 0 ≤ positions[i][0], positions[i][1] ≤ 100
- Answers within 10-5 of the actual value will be accepted
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code