TRT
Sign in
mediumAdvancedLeetCode#Floyd-Warshall

Find the city with the smallest number of neighbors at a threshold distance

Compute all-pairs distances with Floyd-Warshall, then count each city's neighbors within a distance limit.

The Runtime Theory Team1 min read
Taught inFloyd-WarshallPro — members onlyFloyd-Warshall computes the shortest path between every pair of vertices with three nested loops over a distance matrix. Its outer loop allows one more intermediate vertex at a time, which is a dynamic program in disguise.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inn = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4

out3

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

out0

Given weighted undirected roads between n cities, return the city with the fewest other cities reachable within distanceThreshold. Break ties by the larger city number.

Before you code

Every city needs distances to every other city: all pairs. With n ≤ 100, Floyd-Warshall's n³ is a million steps.

Hints

  1. Initialize d with 0 on the diagonal, edge weights both ways and infinity elsewhere.
  2. Run the triple loop with k outermost.
  3. For each city, count the others with d[i][j] <= threshold; keep the smallest count, preferring larger indexes on ties.

Production & complexity notes

When solving Find the city with the smallest number of neighbors at a threshold distance on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Floyd-Warshall to reinforce the underlying pattern.

What it practices

All-pairs shortest paths, from Floyd-Warshall.

Not started

Sign in to save your learning progress.

Sign in to save