SDE & MLE Prep

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

Problem

Cities 0…n − 1 are joined by weighted two-way edges. For each city, count the cities reachable through paths of total weight ≤ distanceThreshold. Return the city with the smallest count; on a tie, the one with the largest number.

Example: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4 → 3

Constraints: n ≤ 100.

All-pairs shortest paths with Floyd–Warshall (dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) for every intermediate k). Count reachable cities within the threshold; ties go to the larger index.

Complexity: O(n³).

class Solution:
    def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
        INF = float("inf")
        d = [[0 if i == j else INF for j in range(n)] for i in range(n)]
        for a, b, w in edges:
            d[a][b] = d[b][a] = w
        for k in range(n):
            for i in range(n):
                for j in range(n):
                    if d[i][k] + d[k][j] < d[i][j]:
                        d[i][j] = d[i][k] + d[k][j]
        best, city = INF, -1
        for i in range(n):
            cnt = sum(d[i][j] <= distanceThreshold for j in range(n)) - 1
            if cnt <= best:
                best, city = cnt, i
        return city