Find the City With the Smallest Number of Neighbors at a Threshold Distance, explained
Find the City With the Smallest Number of Neighbors at a Threshold Distance gives you n cities joined by two-way roads of different lengths and a distance limit, and asks which city can reach the fewest other cities by a shortest route no longer than the limit, choosing the highest-numbered city on a tie. Compute shortest distances between every pair, either with Floyd-Warshall in O(n³) or with Dijkstra from each city, then count per city and pick by the tie rule.
By Evin JohnPublished 8 min read
The problem, reworded
There are n cities numbered 0 to n - 1, and a list of two-way roads, each with a length. Two cities are neighbors at the threshold if the shortest route between them is no longer than a given limit. For each city, count how many other cities are its neighbors in that sense. Return the city with the smallest count, and if several share it, the one with the largest number.
road length
0 - 1 2
1 - 2 2
2 - 3 5
3 - 4 1
0 - 2 3
shortest distances
0 1 2 3 4
0 0 2 3 8 9
1 2 0 2 7 8
2 3 2 0 5 6
3 8 7 5 0 1
4 9 8 6 1 0With a limit of 4, cities 0, 1 and 2 each reach two others, while cities 3 and 4 each reach only one. Both 3 and 4 have the smallest count, so the tie rule picks 4. Note that the direct road from 0 to 2 has length 3 while the route through 1 has length 4: the shortest distance is 3, and that is the one that counts.
What the interviewer is checking
This problem tests whether you know an all-pairs shortest path method and can justify choosing it. Interviewers listen for you to reject breadth-first search because the roads have lengths, to describe Floyd-Warshall's loop order correctly, and to apply the tie rule without a separate sorting step. A good follow-up discussion compares Floyd-Warshall with running Dijkstra from each city, depending on how many roads there are.
All pairs at once: Floyd-Warshall
Start with a table where the distance from a city to itself is 0, a road gives its length (the shorter one if a pair appears twice), and everything else is infinity. Then, for each city k in turn, allow routes to pass through k: for every pair i and j, if going from i to k and then k to j is shorter than the current i to j, take it. After all n rounds, every entry is a true shortest distance. The order matters: k must be the outer loop, because each round extends the set of cities allowed in the middle of a route.
def find_city_floyd(n, roads, limit):
INF = float("inf")
dist = [[0 if i == j else INF for j in range(n)] for i in range(n)]
for a, b, w in roads:
dist[a][b] = min(dist[a][b], w)
dist[b][a] = min(dist[b][a], w)
for k in range(n): # allow city k as a stop in between
dk = dist[k]
for i in range(n):
via = dist[i][k]
if via == INF:
continue
di = dist[i]
for j in range(n):
if via + dk[j] < di[j]:
di[j] = via + dk[j]
best_city, best_count = -1, n + 1
for i in range(n):
count = sum(1 for j in range(n) if j != i and dist[i][j] <= limit)
if count <= best_count: # "<=" lets a later city win ties
best_city, best_count = i, count
return best_city#include <algorithm>
#include <climits>
#include <vector>
int findTheCity(int n, const std::vector<std::vector<int>>& roads, int limit) {
const long long INF = LLONG_MAX / 4;
std::vector<std::vector<long long>> dist(n, std::vector<long long>(n, INF));
for (int i = 0; i < n; ++i) dist[i][i] = 0;
for (const auto& r : roads) {
dist[r[0]][r[1]] = std::min<long long>(dist[r[0]][r[1]], r[2]);
dist[r[1]][r[0]] = std::min<long long>(dist[r[1]][r[0]], r[2]);
}
for (int k = 0; k < n; ++k) // k = the stop we may now pass through
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
int bestCity = -1, bestCount = n + 1;
for (int i = 0; i < n; ++i) {
int count = 0;
for (int j = 0; j < n; ++j)
if (j != i && dist[i][j] <= limit) ++count;
if (count <= bestCount) { // ties go to the larger index
bestCount = count;
bestCity = i;
}
}
return bestCity;
}Infinity is LLONG_MAX / 4 rather than LLONG_MAX so that adding two unreachable distances cannot overflow. In Python, float("inf") handles that for free, and skipping rows where dist[i][k] is infinite saves time on sparse maps.
One Dijkstra per city, stopping at the limit
Floyd-Warshall always does n³ work, even if there are only a handful of roads. The alternative is a Dijkstra search from each city that never records a distance above the limit, since nothing beyond it is counted. Each search costs O(E log V) at most, so the total is O(V · E log V), which beats n³ when roads are sparse. It also tends to stop early when the limit is small.
import heapq
def find_city_dijkstra(n, roads, limit):
links = [[] for _ in range(n)]
for a, b, w in roads:
links[a].append((b, w))
links[b].append((a, w))
def reachable_from(src):
dist = {src: 0}
heap = [(0, src)]
while heap:
d, node = heapq.heappop(heap)
if d > dist[node]:
continue
for nxt, w in links[node]:
nd = d + w
if nd <= limit and nd < dist.get(nxt, nd + 1):
dist[nxt] = nd # only keep cities within the limit
heapq.heappush(heap, (nd, nxt))
return len(dist) - 1 # minus the start city itself
best_city, best_count = -1, n + 1
for i in range(n):
count = reachable_from(i)
if count <= best_count:
best_city, best_count = i, count
return best_cityWhy the tie rule needs no sorting
Cities are checked in increasing order, and the comparison uses less than or equal. Any later city with the same count replaces the earlier one, so the last city holding the minimum wins, which is the largest number. Using a strict less-than instead returns the smallest number on a tie, the most common wrong answer on this problem.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Floyd-Warshall | O(V³) | O(V²) |
| Dijkstra from every city | O(V · E log V) | O(V + E) |
| Bellman-Ford from every city | O(V² · E) | O(V) |
Edge cases
- Limit 0: with positive road lengths no other city is within reach, every count is 0, and the answer is n - 1.
- Isolated cities: their count is 0, so they win unless a higher-numbered city also has 0.
- Two roads between the same pair: keep the shorter one.
- A long direct road and a shorter detour: only the shortest distance is compared with the limit.
- Large road lengths: use 64-bit integers in C++ so sums do not overflow.
Mistakes to avoid
- Putting the k loop inside the i and j loops, which gives wrong distances.
- Counting the city itself as one of its neighbors.
- Using breadth-first search, which counts roads rather than length.
- Breaking ties toward the smaller number with a strict comparison.
- Adding road lengths only in one direction, although roads are two-way.
Follow-up questions
- Roads are one-way. Set only dist[a][b]; Floyd-Warshall works unchanged on directed graphs.
- Return the counts for every city. You already have them; return the list instead of the winner.
- Many different limits. Compute all distances once, sort each city's row, and binary search per limit.
- One-way roads that may be negative. Floyd-Warshall still works if there is no negative cycle, and Dijkstra does not. A negative two-way road is itself a negative cycle, so this only makes sense for one-way roads.
How to explain it
Fictional example
- Candidate
- I need shortest distances between every pair of cities, so with n this small I'll use Floyd-Warshall: allow each city in turn as a midpoint and relax every pair.
- Candidate
- Then for each city I count others within the limit. I scan cities in order and update on less-than-or-equal, so the largest index wins a tie.
- Candidate
- That's O(n³). If roads were sparse and n large, I'd run a Dijkstra from each city and stop expanding past the limit instead.
Related walkthroughs
Path with Maximum Probability and Path With Minimum Effort adapt Dijkstra from a single start. Bus Routes is the unweighted counterpart, where waves of breadth-first search are enough. See the coding problems hub for every walkthrough.
Practicing shortest paths with Natively
Tables like the distance matrix above are easy to get wrong by hand. In practice on Mac or Windows, you can let Natively read the road list from a screenshot, ask it to fill in the matrix round by round, and compare it with your own. It can propose code for Floyd-Warshall or the Dijkstra version, and the mock session's transcript is saved so you can review how you explained the tie rule. The AI interview assistant page explains more.
Questions people ask
How do you solve Find the City With the Smallest Number of Neighbors?
Compute shortest distances between every pair of cities with Floyd-Warshall or with Dijkstra from each city, count the other cities within the limit for each one, and return the city with the smallest count, preferring the larger number on ties.
Why is the tie rule handled with less-than-or-equal?
Cities are checked in increasing order, so updating on less-than-or-equal lets a later city with the same count replace an earlier one, which picks the largest number.
Should I use Floyd-Warshall or Dijkstra here?
Floyd-Warshall is O(n³) and short to write, which suits small n. Dijkstra from each city, cut off at the limit, is faster when there are few roads.
Can breadth-first search solve this problem?
No. Roads have different lengths, so counting roads does not give shortest distances.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
