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

Medium Topics Company Tags

There are n cities labeled 0 through n - 1. Each entry [from, to, weight] in edges is a bidirectional road of length weight. The length of a route is the sum of its road lengths.

For each city, count the other cities that can be reached by a route of total length at most distanceThreshold. Return the label of a city with the smallest count. If several cities tie, return the greatest label.

A city does not count itself. The graph may be disconnected.

Example 1:

Find the City With the Smallest Number of Neighbors at a Threshold Distance, example 1: illustration of the example

Input: n = 4
edges = [[0,1,2],[1,2,2],[2,3,2]]
distanceThreshold = 2

Output: 3

Explanation: Cities 0 and 3 can each reach one other city within distance 2. Cities 1 and 2 can each reach two. The endpoints tie for the smallest count, so return the greater label, 3.

Example 2:

Find the City With the Smallest Number of Neighbors at a Threshold Distance, example 2: illustration of the example

Input: n = 5
edges = [[0,1,1],[1,2,1],[2,3,1]]
distanceThreshold = 4

Output: 4

Explanation: City 4 is isolated and reaches no other city. Each of cities 0 through 3 can reach all three others in its component, so city 4 has the smallest count.

Example 3:

Find the City With the Smallest Number of Neighbors at a Threshold Distance, example 3: illustration of the example

Input: n = 4
edges = [[0,1,5],[1,2,1],[2,3,1]]
distanceThreshold = 2

Output: 0

Explanation: City 0 cannot reach another city within distance 2 because its only road has length 5. Cities 1, 2, and 3 can each reach the other two, so return city 0.

Constraints:

  • 2 <= n <= 100
  • 1 <= edges.length <= n * (n - 1) / 2
  • edges[i].length == 3
  • 0 <= from < to < n
  • 1 <= weight, distanceThreshold <= 10000
  • No pair of cities has more than one road.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.