Find the City With the Smallest Number of Neighbors at a Threshold Distance - Problem
There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.
Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold. If there are multiple such cities, return the city with the greatest number.
Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.
Input & Output
Example 1 — Basic Linear Graph
$
Input:
n = 4, edges = [[0,1,3],[1,2,2],[2,3,1]], distanceThreshold = 4
›
Output:
0
💡 Note:
City 0 can reach city 1 (distance 3). City 1 can reach cities 0,2,3 (distances 3,2,3). City 2 can reach cities 1,3 (distances 2,1). City 3 can reach cities 1,2 (distances 3,1). City 0 has the fewest reachable cities (1), so return 0.
Example 2 — Disconnected Components
$
Input:
n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2]], distanceThreshold = 2
›
Output:
3
💡 Note:
Within threshold 2: City 0 can reach city 1 (distance 2). City 1 can reach cities 0,4 (distances 2,2). City 2 has no reachable neighbors. City 3 has no reachable neighbors. City 4 can reach city 1 (distance 2). Cities 2 and 3 both have 0 reachable neighbors, so return the larger index 3.
Example 3 — Single City
$
Input:
n = 1, edges = [], distanceThreshold = 1
›
Output:
0
💡 Note:
Only one city exists, so it has 0 reachable neighbors and is the answer by default.
Constraints
- 2 ≤ n ≤ 100
- 1 ≤ edges.length ≤ n × (n - 1) / 2
- edges[i].length == 3
- 0 ≤ fromi < toi < n
- 1 ≤ weighti, distanceThreshold ≤ 104
- All pairs (fromi, toi) are distinct.
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code