K Centers Problem

Pattern: Candy and assign cookies

medium

Choosing k cities as centres to make the farthest city-to-centre distance smallest is hard to solve exactly, so this is the classic greedy approximation: start with city 0, then repeatedly make the city farthest from all chosen centres a centre. Return the largest distance left; it is at most twice the best possible.

The problem

dist is a matrix of distances between n cities. Choose k cities as centres with this rule: the first is city 0; each next one is the city farthest from its nearest centre (lowest number on ties). Return the largest distance from any city to its nearest centre. With the 4-city matrix above and k = 2 the answer is 5. The linked page could not be read when this guide was written, so the rules below are this guide's own statement of the task.

Think first

  • Why not try every set of k centres?
  • Which city is served worst right now?
  • What should happen to it?

Hints

    Brute force, and why it fails

    Try every set of k centres: exponential.

    The key insight

    Picking the worst-served city each time guarantees an answer at most twice the optimum (when distances obey the triangle inequality), and it is fast.

    Dry run

    near0 4 8 5

    4 cities, k = 2. Centre 0. Distances to it: 0, 4, 8, 5.

    Step 1 of 3

    The plan

    near = dist[0]
    repeat k - 1 times: far = argmax near; near[i] = min(near[i], dist[far][i])
    return max(near)
    

    Complexity

    Time
    O(n × k)
    Space
    O(n)

    Each new centre updates every city once.

    Edge cases

    • k = 1: the farthest city from city 0.
    • k = n: 0.
    • Ties: the lowest number.
    I've built my logic, show the code

    Java

    class Solution {
        public int kCenters(int[][] dist, int k) {
            int n = dist.length;
            int[] near = dist[0].clone();           // distance from each city to its nearest centre; city 0 is the first
            for (int c = 1; c < k; c++) {
                int far = 0;
                for (int i = 1; i < n; i++) if (near[i] > near[far]) far = i;   // the worst-served city (lowest index on ties)
                for (int i = 0; i < n; i++) near[i] = Math.min(near[i], dist[far][i]);   // becomes a centre
            }
            int worst = 0;
            for (int x : near) worst = Math.max(worst, x);
            return worst;
        }
    }

    C++

    class Solution {
    public:
        int kCenters(vector<vector<int>>& dist, int k) {
            int n = static_cast<int>(dist.size());
            vector<int> near(dist[0]);              // distance from each city to its nearest centre; city 0 is the first
            for (int c = 1; c < k; c++) {
                int far = 0;
                for (int i = 1; i < n; i++) if (near[i] > near[far]) far = i;   // the worst-served city (lowest index on ties)
                for (int i = 0; i < n; i++) near[i] = min(near[i], dist[far][i]);   // becomes a centre
            }
            return *max_element(near.begin(), near.end());
        }
    };

    Python

    class Solution:
        def kCenters(self, dist: list[list[int]], k: int) -> int:
            n = len(dist)
            near = list(dist[0])                    # distance from each city to its nearest centre; city 0 is the first
            for _ in range(k - 1):
                far = max(range(n), key=lambda i: (near[i], -i))   # the worst-served city (lowest index on ties)
                near = [min(near[i], dist[far][i]) for i in range(n)]   # becomes a centre
            return max(near)

    Common mistakes

    • Starting from a different city, which changes the answer.
    • Forgetting to update the nearest distances after each new centre.

    Similar problems