Find the City With the Smallest Number of Neighbors at a Threshold Distance

Pattern: Shortest paths

medium

Compute all-pairs shortest distances with Floyd-Warshall. For each city, count the other cities within the threshold. Return the city with the fewest such neighbours, choosing the larger number on a tie.

The problem

Given n cities and two-way weighted roads, return the city that can reach the fewest other cities within distanceThreshold. On a tie, return the city with the greatest number. Vertices are numbered from 0 and each edge is [u, v, weight].

Think first

  • What distances do you need?
  • Which algorithm gives them all at once?
  • How do you break ties?

Hints

    Brute force, and why it fails

    Dijkstra from every city: O(V × E log V), better on sparse graphs.

    The key insight

    Once all-pairs distances are known, each city's count is one row scan.

    Dry run

    4 cities, edges 0-1 (3), 1-2 (1), 1-3 (4), 2-3 (1); threshold 4.

    Step 1 of 3

    The plan

    Floyd-Warshall; for each i: count j != i with d[i][j] <= threshold; keep the smallest count (<= keeps the larger i)
    

    Complexity

    Time
    O(V³)
    Space
    O(V²)

    Floyd-Warshall dominates.

    Edge cases

    • No roads: every city reaches 0; answer n - 1.
    • A large threshold.
    • Two cities.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int findTheCity(int n, int[][] edges, int distanceThreshold) {
            final int INF = Integer.MAX_VALUE / 2;
            int[][] d = new int[n][n];
            for (int[] row : d) Arrays.fill(row, INF);
            for (int i = 0; i < n; i++) d[i][i] = 0;
            for (int[] e : edges) d[e[0]][e[1]] = d[e[1]][e[0]] = Math.min(d[e[0]][e[1]], e[2]);
            for (int k = 0; k < n; k++)             // all-pairs shortest distances
                for (int i = 0; i < n; i++)
                    for (int j = 0; j < n; j++) d[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]);
            int best = -1, fewest = Integer.MAX_VALUE;
            for (int i = 0; i < n; i++) {
                int reach = 0;
                for (int j = 0; j < n; j++) if (j != i && d[i][j] <= distanceThreshold) reach++;
                if (reach <= fewest) { fewest = reach; best = i; }   // <= keeps the larger number on a tie
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
            const int INF = INT_MAX / 2;
            vector<vector<int>> d(n, vector<int>(n, INF));
            for (int i = 0; i < n; i++) d[i][i] = 0;
            for (const vector<int>& e : edges) d[e[0]][e[1]] = d[e[1]][e[0]] = min(d[e[0]][e[1]], e[2]);
            for (int k = 0; k < n; k++)             // all-pairs shortest distances
                for (int i = 0; i < n; i++)
                    for (int j = 0; j < n; j++) d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
            int best = -1, fewest = INT_MAX;
            for (int i = 0; i < n; i++) {
                int reach = 0;
                for (int j = 0; j < n; j++) if (j != i && d[i][j] <= distanceThreshold) reach++;
                if (reach <= fewest) { fewest = reach; best = i; }   // <= keeps the larger number on a tie
            }
            return best;
        }
    };

    Python

    class Solution:
        def findTheCity(self, n: int, edges: list[list[int]], distanceThreshold: int) -> int:
            INF = float("inf")
            d = [[0 if i == j else INF for j in range(n)] for i in range(n)]
            for u, v, w in edges:
                d[u][v] = d[v][u] = min(d[u][v], w)
            for k in range(n):                      # all-pairs shortest distances
                for i in range(n):
                    for j in range(n):
                        d[i][j] = min(d[i][j], d[i][k] + d[k][j])
            best, fewest = -1, INF
            for i in range(n):
                reach = sum(1 for j in range(n) if j != i and d[i][j] <= distanceThreshold)
                if reach <= fewest:                 # <= keeps the larger number on a tie
                    fewest, best = reach, i
            return best

    Common mistakes

    • Counting the city itself.
    • Breaking ties towards the smaller number.

    Similar problems