#1334

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

Medium Floyd-Warshall

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

In a weighted undirected graph of n cities, count for each city how many others are within distanceThreshold. Return the city with the fewest such neighbours; on ties, the one with the greatest number.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: which city can reach the fewest others within the distance limit?

Why this works: Floyd-Warshall gives all-pairs shortest paths by trying every city k as a middle stop.

Example: 4 cities, threshold 4

reachable counts: 0→2, 1→3, 2→3, 3→2tie between 0 and 3 → pick the larger, 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Putting k in an inner loop — k must be the outermost loop for Floyd-Warshall to be correct.

Solve on LeetCode ↗
Complexity
  • Time: O(n³).
  • Space: O(n²).
Topic: Graphs
🎬 Episodes 74–85: video coming soon