Best Position for a Service Centre — LeetCode 1515 Python Solution
- Problem
- #1515
- Pattern
- Math and Number Theory
- Reading time
- 5 min
- Source
- leetcode.com
The 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.
Example
- Input
- positions = [[0,1],[1,0],[1,2],[2,1]]
- Output
- 4.00000
- Explanation
- As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.
Python solution
class Solution:
def getMinDistSum(self, positions: List[List[int]]) -> float:
n = len(positions)
x = y = 0
for x1, y1 in positions:
x += x1
y += y1
x, y = x / n, y / n
decay = 0.999
eps = 1e-6
alpha = 0.5
while 1:
grad_x = grad_y = 0
dist = 0
for x1, y1 in positions:
a = x - x1
b = y - y1
c = sqrt(a * a + b * b)
grad_x += a / (c + 1e-8)
grad_y += b / (c + 1e-8)
dist += c
dx = grad_x * alpha
dy = grad_y * alpha
x -= dx
y -= dy
alpha *= decay
if abs(dx) <= eps and abs(dy) <= eps:
return distComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1515. Best Position for a Service Centre is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Geometry.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1515. Best Position for a Service Centre?
- LeetCode 1515. Best Position for a Service Centre is rated Hard on LeetCode.
- What topics does LeetCode 1515. Best Position for a Service Centre cover?
- LeetCode 1515. Best Position for a Service Centre is tagged Geometry, Array, Math and Randomized on LeetCode.