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

medium

There are n cities (0 .. n-1) connected by bidirectional weighted edges[i] = [u, v, w]. Return the city with the smallest number of other cities reachable within a total distance ≤ threshold. If several cities tie, return the one with the greatest index.

Hints

You need shortest distances between all pairs, not just direct edges.
Compute the all-pairs matrix (Floyd-Warshall), then count each city's neighbours within threshold.
Return the city with the fewest; on ties pick the largest index (scan with ≤).

Common doubts

A city might reach another cheaply via intermediate cities even without a direct road, so you need true shortest distances.
Scanning cities 0..n-1, using ≤ means a later city with an equal count overwrites the earlier best, so the greatest index survives.
Both give the same matrix; Floyd-Warshall is simpler to code and fine here since n is small and graphs can be dense.

Interview follow-ups

Reachability becomes asymmetric; count only cities reachable FROM each city.
Prefer Dijkstra per source (with a heap) on sparse graphs; Floyd-Warshall's O(n³) becomes prohibitive.

Fun facts

  • LeetCode 1334 — a clean 'all-pairs then count' application of Floyd-Warshall.
  • The ≤ tie-break trick is a tidy way to encode 'largest index wins' in one pass.

Asked at

AmazonGoogle
Frequently Sometimes Occasionally
Example 1
Input: n = 4, edges = [[0,1,3],[1,2,1],[2,3,4],[0,3,7]], threshold = 4
Output: 3
City 3 reaches only city 2 within distance 4 — the fewest.
Example 2
Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], threshold = 2
Output: 0
City 0 reaches the fewest (just city 1) within distance 2.
Constraints

- 1 <= n <= 100 - 0 <= edges.length <= n*(n-1)/2 - 1 <= w <= 10^4 - 0 <= threshold <= 10^4

Solve this problem →