Find the City With the Smallest Number of Neighbors at a Threshold Distance (LeetCode 1334): Solution and Explanation
Given weighted two-way roads between n cities and a distance limit, find the city that can reach the fewest other cities within that limit, breaking ties toward the larger city number.
Intuition
A city's neighbour count depends on its shortest distance to every other city. So the real work is the all-pairs shortest path table; counting is easy afterwards.
A direct road is not always the shortest way. Two short roads through a third city can beat one long road, which is why you cannot just look at edge weights.
Floyd-Warshall builds the table by allowing one more stopover city at a time. After round k, dist[i][j] is the shortest path that only uses cities 0..k in the middle. After the last round, every city is allowed, so the table is exact.
With at most 100 cities, n³ is one million updates, which is quick. Then scan cities in increasing order and use <= when comparing counts, so a later city with the same count takes over.
Approach: Floyd-Warshall, then count
- Create an
n x ntable with infinity everywhere, 0 on the diagonal, and the road length in both directions for each edge. - For each stopover
kfrom 0 to n - 1, and each pair(i, j), replacedist[i][j]withdist[i][k] + dist[k][j]when that is smaller. - For each city
i, count the citiesj != iwithdist[i][j] <= distanceThreshold. - Keep the city whose count is less than or equal to the best count seen so far, and return it.
Step-by-step example
n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
- Direct roads give dist[0][1] = 3, dist[1][2] = 1, dist[1][3] = 4 and dist[2][3] = 1. Everything else between different cities is infinity.
- Stopover 1: 0 -> 1 -> 2 gives dist[0][2] = 4 and 0 -> 1 -> 3 gives dist[0][3] = 7.
- Stopover 2: 1 -> 2 -> 3 costs 2, shorter than the direct road of 4, and 0 -> 2 -> 3 costs 5, shorter than 7.
- With threshold 4, city 0 reaches 1 and 2, city 1 reaches 0, 2 and 3, city 2 reaches 0, 1 and 3, and city 3 reaches 1 and 2.
- Cities 0 and 3 both have 2 neighbours. The scan replaces 0 with 3 because 2 <= 2, so the answer is 3.
Code: Python, Java, C++
1class Solution:
2 def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
3 INF = float('inf')
4 dist = [[INF] * n for _ in range(n)]
5 for i in range(n):
6 dist[i][i] = 0
7 for u, v, w in edges:
8 dist[u][v] = dist[v][u] = w
9 for k in range(n):
10 for i in range(n):
11 for j in range(n):
12 if dist[i][k] + dist[k][j] < dist[i][j]:
13 dist[i][j] = dist[i][k] + dist[k][j]
14 best, best_count = -1, n + 1
15 for i in range(n):
16 count = sum(1 for j in range(n) if j != i and dist[i][j] <= distanceThreshold)
17 if count <= best_count:
18 best, best_count = i, count
19 return best1class Solution {
2 public int findTheCity(int n, int[][] edges, int distanceThreshold) {
3 final int INF = 1_000_000_000;
4 int[][] dist = new int[n][n];
5 for (int i = 0; i < n; i++) {
6 Arrays.fill(dist[i], INF);
7 dist[i][i] = 0;
8 }
9 for (int[] e : edges) {
10 dist[e[0]][e[1]] = e[2];
11 dist[e[1]][e[0]] = e[2];
12 }
13 for (int k = 0; k < n; k++) {
14 for (int i = 0; i < n; i++) {
15 for (int j = 0; j < n; j++) {
16 if (dist[i][k] + dist[k][j] < dist[i][j]) {
17 dist[i][j] = dist[i][k] + dist[k][j];
18 }
19 }
20 }
21 }
22 int best = -1, bestCount = n + 1;
23 for (int i = 0; i < n; i++) {
24 int count = 0;
25 for (int j = 0; j < n; j++) {
26 if (j != i && dist[i][j] <= distanceThreshold) count++;
27 }
28 if (count <= bestCount) {
29 best = i;
30 bestCount = count;
31 }
32 }
33 return best;
34 }
35}1class Solution {
2public:
3 int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
4 const int INF = 1000000000;
5 vector<vector<int>> dist(n, vector<int>(n, INF));
6 for (int i = 0; i < n; i++) dist[i][i] = 0;
7 for (auto& e : edges) {
8 dist[e[0]][e[1]] = e[2];
9 dist[e[1]][e[0]] = e[2];
10 }
11 for (int k = 0; k < n; k++) {
12 for (int i = 0; i < n; i++) {
13 for (int j = 0; j < n; j++) {
14 if (dist[i][k] + dist[k][j] < dist[i][j]) {
15 dist[i][j] = dist[i][k] + dist[k][j];
16 }
17 }
18 }
19 }
20 int best = -1, bestCount = n + 1;
21 for (int i = 0; i < n; i++) {
22 int count = 0;
23 for (int j = 0; j < n; j++) {
24 if (j != i && dist[i][j] <= distanceThreshold) count++;
25 }
26 if (count <= bestCount) {
27 best = i;
28 bestCount = count;
29 }
30 }
31 return best;
32 }
33};Time and space complexity
O(n^3)
Three nested loops over the cities fill the table, and counting adds O(n^2).
O(n^2)
The distance table has one entry per pair of cities.
Other approaches
Dijkstra from every city (time O(n * E log n), space O(n + E))
Run Dijkstra with a heap from each city and count distances within the threshold. Faster on sparse graphs, but more code than three loops.
Bellman-Ford from every city (time O(n^2 * E), space O(n))
Relax every edge n - 1 times from each source. Correct but the slowest choice here.
Common mistakes
- Putting the
kloop on the inside. The stopover loop must be the outermost loop, or the table is not built in the right order. - Overflow when adding two infinities with a sentinel like
Integer.MAX_VALUE. Use a value such as 10^9 so the sum still fits in a 32-bit int, or skip infinite entries. - Breaking ties toward the smaller index. Use
<=while scanning upward, or scan from the largest city down with<. - Forgetting that roads go both ways. Set both
dist[u][v]anddist[v][u].
Frequently asked questions
Why does the stopover loop have to be outermost?
Round k assumes every pair's distance through stopovers 0..k-1 is already final. Only the outer k loop guarantees that before stopover k is tried.
Is Dijkstra better here?
For n up to 100 both pass easily. Floyd-Warshall is shorter to write and has no heap. Dijkstra from each source wins when the graph is large and sparse.
Does the threshold change the shortest paths?
No. The shortest distances are computed first without any limit, and only then compared to the threshold. A path that passes through far cities can still end close enough.
Can a city with no roads be the answer?
Yes. It reaches 0 cities, which is the smallest possible count. If several cities reach 0, the largest of them is returned.