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: 3
💡 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,0 (distances 2,1,5). City 3 can reach cities 2,1 (distances 1,3). Cities 0 and 3 both have the fewest reachable cities (1 and 2 respectively), so we return the larger index 3.
Example 2 — Disconnected Components
$ Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2]], distanceThreshold = 2
Output: 0
💡 Note: Within threshold 2: City 0 can reach city 1. City 1 can reach city 0. Cities 2,3,4 have no neighbors within threshold 2. City 0 has 1 neighbor, others have 0 or 1, so return the largest index among those with minimum count.
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
Find City With Fewest Neighbors Within Distance Threshold01233211 neighbor3 neighbors3 neighbors2 neighborsDistance Threshold = 4Cities with minimum neighbors:City 0: 1 neighbor, City 3: 2 neighborsChoose city 0 (fewer neighbors)Result: City 0 is most isolated
Understanding the Visualization
1
Input Graph
Cities connected by weighted edges
2
Calculate Distances
Find shortest paths between all city pairs
3
Count & Select
Count neighbors within threshold, return city with minimum count
Key Takeaway
🎯 Key Insight: Use Floyd-Warshall to find all shortest paths, then count reachable neighbors for each city
Asked in
Amazon 15 Google 12 Microsoft 8 Facebook 6
18.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen