oneby7

Advanced Graphs Weighted shortest paths

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

Medium

There are n cities, numbered from 0 to n − 1. You are given a list edges of roads, where edges[i] = [u, v, w] is a road of length w between cities u and v. A road can be used in both directions.

The distance between two cities is the length of the shortest route between them, over any number of roads. For each city, count the other cities whose distance from it is at most distanceThreshold. Return the city with the smallest count. If several cities share the smallest count, return the one with the largest number.

A city that no route reaches is never counted, however large the threshold is.

Example 1

223261012345

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

Output: 4

Explanation: City 4 reaches only city 3 within a distance of 4. City 2 is 5 away from it and city 5 is 6 away. Every other city reaches at least two cities: city 5, for example, reaches city 0 at 1 and city 1 at 3.

Example 2

22101234

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

Output: 4

Explanation: Cities 0, 1 and 2 each reach the other two, since city 0 is 4 away from city 2. Cities 3 and 4 are joined only to each other, so each has one. They tie, and the answer is the larger number, 4.

Example 3

46190123

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

Output: 3

Explanation: Two roads join cities 0 and 1, and the shorter one, of length 4, is the one a route uses. City 0 then reaches city 2 at exactly 4 + 6 = 10, which counts. Cities 0 and 3 both reach two cities, so the answer is 3.

Check your understanding

Work out the answer for this input before you write any code.

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

Constraints

  • 1 ≤ n ≤ 400
  • 0 ≤ edges.length ≤ 105
  • edges[i] = [u, v, w], with 0 ≤ u, v ≤ n − 1, u ≠ v and 1 ≤ w ≤ 104
  • 1 ≤ distanceThreshold ≤ 104
  • Two roads can join the same two cities.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.