Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 following formula is minimized:
Answers within 10-5 of the actual value will be accepted.
Example 1:
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.
Example 2:
Input: positions = [[1,1],[3,3]] Output: 2.82843 Explanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843
Constraints:
1 <= positions.length <= 50positions[i].length == 20 <= xi, yi <= 100Problem summary: 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 following formula is minimized: Answers within 10-5 of the actual value will be accepted.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math
[[0,1],[1,0],[1,2],[2,1]]
[[1,1],[3,3]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1515: Best Position for a Service Centre
class Solution {
public double getMinDistSum(int[][] positions) {
int n = positions.length;
double x = 0, y = 0;
for (int[] p : positions) {
x += p[0];
y += p[1];
}
x /= n;
y /= n;
double decay = 0.999;
double eps = 1e-6;
double alpha = 0.5;
while (true) {
double gradX = 0, gradY = 0;
double dist = 0;
for (int[] p : positions) {
double a = x - p[0], b = y - p[1];
double c = Math.sqrt(a * a + b * b);
gradX += a / (c + 1e-8);
gradY += b / (c + 1e-8);
dist += c;
}
double dx = gradX * alpha, dy = gradY * alpha;
if (Math.abs(dx) <= eps && Math.abs(dy) <= eps) {
return dist;
}
x -= dx;
y -= dy;
alpha *= decay;
}
}
}
// Accepted solution for LeetCode #1515: Best Position for a Service Centre
func getMinDistSum(positions [][]int) float64 {
n := len(positions)
var x, y float64
for _, p := range positions {
x += float64(p[0])
y += float64(p[1])
}
x /= float64(n)
y /= float64(n)
const decay float64 = 0.999
const eps float64 = 1e-6
var alpha float64 = 0.5
for {
var gradX, gradY float64
var dist float64
for _, p := range positions {
a := x - float64(p[0])
b := y - float64(p[1])
c := math.Sqrt(a*a + b*b)
gradX += a / (c + 1e-8)
gradY += b / (c + 1e-8)
dist += c
}
dx := gradX * alpha
dy := gradY * alpha
if math.Abs(dx) <= eps && math.Abs(dy) <= eps {
return dist
}
x -= dx
y -= dy
alpha *= decay
}
}
# Accepted solution for LeetCode #1515: Best Position for a Service Centre
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 dist
// Accepted solution for LeetCode #1515: Best Position for a Service Centre
struct Solution;
use rand::prelude::*;
impl Solution {
fn get_min_dist_sum(positions: Vec<Vec<i32>>) -> f64 {
let mut rng = thread_rng();
let mut x = 50.0;
let mut y = 50.0;
let mut r = 50.0;
let mut prev = Self::dist(&positions, x, y);
for _ in 0..25 {
for _ in 0..25 {
let xx = x + rng.gen_range(-1.0, 1.0) * r;
let yy = y + rng.gen_range(-1.0, 1.0) * r;
let next = Self::dist(&positions, xx, yy);
if next < prev {
prev = next;
x = xx;
y = yy;
}
}
r *= 0.5;
}
prev
}
fn dist(positions: &[Vec<i32>], x: f64, y: f64) -> f64 {
positions
.iter()
.map(|v| (((v[0] as f64 - x).powi(2) + (v[1] as f64 - y).powi(2)).sqrt()))
.sum::<f64>()
}
}
#[test]
fn test() {
use assert_approx_eq::assert_approx_eq;
let positions = vec_vec_i32![[0, 1], [1, 0], [1, 2], [2, 1]];
let res = 4.0;
assert_approx_eq!(Solution::get_min_dist_sum(positions), res, 1.0e-5);
let positions = vec_vec_i32![[1, 1], [3, 3]];
let res = 2.82843;
assert_approx_eq!(Solution::get_min_dist_sum(positions), res, 1.0e-5);
let positions = vec_vec_i32![[1, 1]];
let res = 0.0;
assert_approx_eq!(Solution::get_min_dist_sum(positions), res, 1.0e-5);
let positions = vec_vec_i32![[1, 1], [0, 0], [2, 0]];
let res = 2.73205;
assert_approx_eq!(Solution::get_min_dist_sum(positions), res, 1.0e-5);
let positions = vec_vec_i32![[0, 1], [3, 2], [4, 5], [7, 6], [8, 9], [11, 1], [2, 12]];
let res = 32.94036;
assert_approx_eq!(Solution::get_min_dist_sum(positions), res, 1.0e-5);
}
// Accepted solution for LeetCode #1515: Best Position for a Service Centre
function getMinDistSum(positions: number[][]): number {
const n = positions.length;
let [x, y] = [0, 0];
for (const [px, py] of positions) {
x += px;
y += py;
}
x /= n;
y /= n;
const decay = 0.999;
const eps = 1e-6;
let alpha = 0.5;
while (true) {
let [gradX, gradY] = [0, 0];
let dist = 0;
for (const [px, py] of positions) {
const a = x - px;
const b = y - py;
const c = Math.sqrt(a * a + b * b);
gradX += a / (c + 1e-8);
gradY += b / (c + 1e-8);
dist += c;
}
const dx = gradX * alpha;
const dy = gradY * alpha;
if (Math.abs(dx) <= eps && Math.abs(dy) <= eps) {
return dist;
}
x -= dx;
y -= dy;
alpha *= decay;
}
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.