#1515Hard~50 min

Best Position for a Service Centre

Time O(n * iter) · Space O(n) · Official statement on LeetCode

cpppython

Solutions

// Time:  O(n * iter), iter is the number of iterations
// Space: O(1)

// see reference:
// - https://en.wikipedia.org/wiki/Geometric_median
// - https://wikimedia.org/api/rest_v1/media/math/render/svg/b3fb215363358f12687100710caff0e86cd9d26b
// Weiszfeld's algorithm
class Solution {
public:
    double getMinDistSum(vector<vector<int>>& positions) {
        static const double EPS = 1e-6;
        pair<double, double> median;
        median.first = (accumulate(cbegin(positions), cend(positions), 0.0,
                                   [](const auto& a, const auto& b) {
                                       return a + b[0];
                                   }) / positions.size());
        median.second = (accumulate(cbegin(positions), cend(positions), 0.0,
                                    [](const auto& a, const auto& b) {
                                        return a + b[1];
                                    }) / positions.size());
        pair<double, double> prev_median = {-1.0, -1.0};
        while (prev_median.first < 0 || norm(median, prev_median) * positions.size() > EPS) {
            const auto& [stopped, new_median] = geometry_median(positions, median);
            if (stopped) {
                break;
            }
            prev_median = median;
            median = new_median;
        }
        return accumulate(cbegin(positions), cend(positions), 0.0,
                          [this, &median](const auto& a, const auto& b) {
                              return a + norm(median, pair(b[0], b[1]));
                          });
    }

private:
    double norm(const pair<double, double>& p1,
                const pair<double, double>& p2) {
        return sqrt((p1.first - p2.first) * (p1.first - p2.first) +
                    (p1.second - p2.second) * (p1.second - p2.second));
    }
        
    pair<bool, pair<double, double>> geometry_median(
        const vector<vector<int>>& positions,
        const pair<double, double>& median) {
        pair<double, double> numerator = {0.0, 0.0};
        double denominator = 0.0;
        for (const auto& p : positions) {
            const auto& l = norm(median, pair(p[0], p[1]));
            if (!l) {
                continue;
            }
            numerator.first += p[0] / l;
            numerator.second += p[1] / l;
            denominator += 1 / l;
        }
        if (denominator == 0.0) {
            return {true, {0.0, 0.0}}; 
        }
        return {false, {numerator.first / denominator, numerator.second / denominator}};
    }
};

// Time:  O(n * iter), iter is the number of iterations
// Space: O(1)
class Solution2 {
public:
    double getMinDistSum(vector<vector<int>>& positions) {
        static const double EPS = 1e-6;
        static const vector<pair<int, int>> DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        pair<double, double> median;
        median.first = (accumulate(cbegin(positions), cend(positions), 0.0,
                                   [](const auto& a, const auto& b) {
                                       return a + b[0];
                                    }) / positions.size());
        median.second = (accumulate(cbegin(positions), cend(positions), 0.0,
                                    [](const auto& a, const auto& b) {
                                        return a + b[1];
                                     }) / positions.size());
        double result = dist(positions, median);
        double delta = max((*max_element(cbegin(positions), cend(positions),
                                         [](const auto& x, const auto& y) { return x[0] < y[0]; }))[0],
                           (*max_element(cbegin(positions), cend(positions),
                                         [](const auto& x, const auto& y) { return x[1] < y[1]; }))[1]) -
                       min((*min_element(cbegin(positions), cend(positions),
                                         [](const auto& x, const auto& y) { return x[0] < y[0]; }))[0],
                           (*min_element(cbegin(positions), cend(positions),
                                         [](const auto& x, const auto& y) { return x[1] < y[1]; }))[1]);
        while (delta > EPS) {
            bool found = false;
            for (const auto& [dx, dy] : DIRECTIONS) {
                pair<double, double> new_median = {median.first + delta * dx, median.second + delta * dy};
                const auto& nd = dist(positions, new_median);
                if (nd < result) {
                    result = nd;
                    median = new_median;
                    found = true;
                    break;
                }
            }
            if (!found) {
                delta /= 2.0;
            }
        }
        return result ;
    }

private:
    double dist(const vector<vector<int>>& positions,
                const pair<double, double>& p) {
        return accumulate(cbegin(positions), cend(positions), 0.0,
                          [&p](const auto& a, const auto& b) {
                              return a + sqrt((p.first - b[0]) * (p.first - b[0]) +
                                              (p.second - b[1]) * (p.second - b[1]));
                          });
    }
};

Beginner Explanation

What is Best Position for a Service Centre?

Best Position for a Service Centre (LeetCode #1515) is a Hard problem that primarily trains geometry.

How to think about it

  1. Restate the goal in your own words before coding.
  2. Work a tiny example by hand so the invariant becomes obvious.
  3. Identify the pattern — this problem aligns with weiszfelds algorithm.
  4. Only then translate the idea into code.

Why this problem matters

Hard problems force you to combine patterns and prove complexity carefully — interview gold. Official solution notes mention: Geometric Median, Gradient Descent, Weiszfeld's Algorithm.

AlgoForge explanations are original teaching notes. Always open the official problem statement on LeetCode for constraints and examples.

Interview Walkthrough

Interview approach for Best Position for a Service Centre

Opening (30–60 seconds)

  • Clarify inputs/outputs and edge cases (empty input, single element, duplicates, overflow).
  • State a brute force so the interviewer knows you can solve it naively.
  • Propose the optimal direction tied to weiszfelds algorithm.

Core solution narrative

  1. Define the state you track (pointers, DP cell, set membership, stack top, etc.).
  2. Explain the transition when you process the next element.
  3. Call out time (O(n * iter)) and space (O(n)) before coding.
  4. Code cleanly; narrate variable names.

What interviewers listen for

  • Correctness on edge cases
  • Complexity honesty
  • Ability to discuss trade-offs (e.g., hash map space vs. sort + two pointers)

Follow-up questions they may ask

  • Can you solve it with less memory?
  • What if the input stream is infinite / doesn't fit in RAM?
  • How would tests look for adversarial inputs?

Optimized Approach

Optimized solution notes

The reference solutions on AlgoForge target O(n * iter) time and O(n) space.

Pattern focus: weiszfelds algorithm

Use the pattern as a checklist:

  • weiszfelds algorithm — confirm the invariant holds after each step

Multiple methods appear in the source solutions — compare them and explain when each is preferable.

Implementation tips

  • Prefer readable names over micro-optimizations in interviews.
  • Extract helpers only when they clarify (e.g., expand-around-center, DFS visit).
  • After AC-level logic, re-scan for off-by-one and null checks.

Complexity Analysis

Complexity

Measure Bound
Time O(n * iter)
Space O(n)

How to justify this in an interview

  • Time: count loops, map/set operations, and recursive branching; state average vs worst case if relevant.
  • Space: include hash maps, recursion stack, and output allocation when the problem asks for it.

If your implementation differs from the reference, re-derive big-O from your code — never memorize a complexity you cannot defend.

Common Mistakes

Common mistakes on Best Position for a Service Centre

  1. Skipping edge cases — empty collections, single-element inputs, max constraints.
  2. Wrong invariant for weiszfelds algorithm — updating state too early or too late.
  3. Mutating input unexpectedly when the problem forbids it.
  4. Off-by-one in windows, ranges, or binary search bounds.
  5. Ignoring overflow / precision for integer arithmetic problems.
  6. Overengineering — jumping to an advanced structure when a simpler approach works.

Alternative Approaches

Alternatives

The source file includes more than one method. Compare:

  1. Primary optimized path — best complexity for typical interviews.
  2. Secondary approach — often brute force, sorting-based, or space-optimized variant.

Practice articulating when you would pick each (constraints, readability, follow-ups).

Edge Cases

Edge cases checklist

  • Minimum input size
  • Maximum input size / time limits
  • Duplicates and already-sorted input
  • Negative numbers / zeros (if applicable)
  • Disconnected structures (graphs/trees)
  • Single path vs branching recursion depth

Pattern Recognition

Spotting this pattern

Signal phrases that point to weiszfelds algorithm:

  • Sorted input or ability to sort without changing the answer class
  • Need for contiguous subarray / substring → consider sliding window
  • Need for O(1) membership → hash set/map
  • Optimal substructure + overlapping subproblems → DP
  • Connectivity / components → graph DFS/BFS or Union-Find

Primary topics: geometry.

Follow-up Interview Questions

Follow-ups

  1. How does the solution change if the input is a stream?
  2. Can you solve it in-place?
  3. What if duplicates must be handled differently?
  4. How would you parallelize the approach?
  5. Design tests that would break a buggy implementation.

Practice Recommendations

What to practice next

  1. Re-solve Best Position for a Service Centre in a second language (cpp, python).
  2. Drill 3–5 more problems tagged geometry.
  3. Teach the solution out loud in under 5 minutes.
  4. Add this problem to your revision calendar in 3 days and 14 days.

Visualization

Conceptual diagram for Best Position for a Service Centre: show input structure (geometry), highlight the moving parts of the weiszfelds algorithm approach, and annotate each step with the maintained invariant and complexity.

Study checklist

  • Read the official problem statement on LeetCode
  • Solve on paper / whiteboard first
  • Implement the weiszfelds algorithm approach
  • Verify edge cases from the checklist
  • State time and space complexity aloud
  • Compare with the AlgoForge reference solution
  • Schedule a revision session

Revision notes

Best Position for a Service Centre (#1515) — Hard. Pattern: weiszfelds algorithm. Complexity: O(n * iter) time / O(n) space. Re-derive the invariant before coding.

FAQs

What is the time complexity of Best Position for a Service Centre?+

The reference solutions aim for O(n * iter) time and O(n) space. Always re-derive complexity from the code you write in the interview.

What pattern does Best Position for a Service Centre use?+

It primarily maps to weiszfelds algorithm, within the broader topic of geometry.

Is Best Position for a Service Centre good for interviews?+

Yes — as a Hard problem it is a solid practice target. Pair it with related problems in the same pattern family for spaced repetition.

Where can I read the official statement?+

Open the official LeetCode page for constraints and examples: https://leetcode.com/problems/best-position-for-a-service-centre/