#1515

Best Position for a Service Centre

Hard
ArrayMathGeometryRandomizedGeometric MedianWeighted Average
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution utilizes an iterative approach to find the geometric median, which minimizes the sum of distances to all points. This is akin to finding the 'average' position that balances the distances effectively.

⚙️

Algorithm

3 steps
  1. 1Step 1: Start with an initial guess for the center position, such as the average of all customer positions.
  2. 2Step 2: Iteratively update the center position by calculating the weighted average of the positions based on their distances.
  3. 3Step 3: Continue until the change in position is smaller than a defined threshold (e.g., 1e-5).
solution.py10 lines
1# Full working Python code
2import numpy as np
3
4def minDistance(positions):
5    positions = np.array(positions)
6    center = np.mean(positions, axis=0)
7    for _ in range(100):
8        distances = np.linalg.norm(positions - center, axis=1)
9        center = np.average(positions, axis=0, weights=1/distances)
10    return np.sum(distances)

Complexity note: This complexity arises because we only iterate through the customer positions a limited number of times (100 iterations), making the overall complexity linear with respect to the number of customers.

  • 1The geometric median minimizes the sum of distances effectively.
  • 2Iterative refinement can lead to a solution without exhaustive search.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.