27 · Shortest Paths

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

Mediumsolve on LeetCode ↗

frequently reported atAmazon

the problem

In plain words

n cities are joined by two-way weighted roads. For each city, count how many other cities are reachable with total distance ≤ distanceThreshold. Return the city with the smallest count; on a tie, return the one with the largest number.

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

out 3

Cities 0 and 3 each reach 2 others; 3 is larger.

in n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2

out 0

  • 2 ≤ n ≤ 100
  • 1 ≤ edges.length ≤ n·(n − 1)/2
  • 1 ≤ weight, distanceThreshold ≤ 10⁴
  • All pairs distinct

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #743
      Network Delay Time
      Mediumin Shortest Paths
    2. #1976