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

Problem Explanation

This problem is about finding the city that has the smallest number of neighboring cities within a given distance threshold. We are given the number of cities and the edges that represent the paths between the cities. Each edge includes the starting city, the destination city, and the weight of the path. The distance between two cities is equal to the sum of the path weights between them.

The task is to find the city with the smallest number of neighboring cities (cities that can be reached from it) that are within a certain distance threshold. If there is more than one such city, we return the city with the greatest number.

For example, if we have 4 cities (0, 1, 2, and 3), and the edges are given as [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], and distance threshold is 4.

The neighboring cities at a distanceThreshold = 4 for each city are: City 0 -> [City 1, City 2] City 1 -> [City 0, City 2, City 3] City 2 -> [City 0, City 1, City 3] City 3 -> [City 1, City 2]

Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number. So the output for this example should be 3.

Solution Approach

The problem can be solved using Floyd-Warshall algorithm. Floyd-Warshall algorithm is a dynamic programming algorithm used to solve the all pairs shortest path problem. The algorithm works by iteratively improving the solution (shortest path between pairs of vertices) until eventually reaching the optimal solution.

The first step is to initialize a distance matrix. The size of the matrix will be n x n, where n is the number of cities. Each element of the matrix dist[i][j] will store the minimum distance between the city i and city j.

We then iterate through the given edges, for each edge we set dist[u][v] and dist[v][u] to the weight of the edge, as the edges are bidirectional.

After that, we use the Floyd-Warshall algorithm to fill the distance matrix. For each city k, we iterate through each pair of cities i and j, if the distance from city i to city j through city k is less than the current distance between city i and city j denoted by dist[i][j], we update the distance in dist[i][j].

Finally, we iterate through all cities and count the number of cities that are reachable within the distance threshold. We keep track of the city with the smallest number of such cities and return this city at the end. If there are multiple cities with the same minimum number of reachable cities, we return the city with the highest number.

Java Solution

In Java programming language, you can define a function like findTheCity within a class like Solution.

1
2java
3class Solution {
4    public int findTheCity(int n, int[][] edges, int distanceThreshold) {
5        int[][] dist = new int[n][n];
6        for (int i = 0; i < n; i++) {
7            Arrays.fill(dist[i], 10001);
8            dist[i][i] = 0;
9        }
10        for (int[] edge : edges) {
11            dist[edge[0]][edge[1]] = edge[2];
12            dist[edge[1]][edge[0]] = edge[2];
13        }
14        for (int k = 0; k < n; k++) {
15            for (int i = 0; i < n; i++) {
16                for (int j = 0; j < n; j++) {
17                    dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
18                }
19            }
20        }
21        int minCity = -1;
22        int minCount = n;
23        for (int i = n - 1; i >= 0; i--) {
24            int count = 0;
25            for (int j = 0; j < n; j++) {
26                if (dist[i][j] <= distanceThreshold) count++;
27            }
28            if (count <= minCount) {
29                minCount = count;
30                minCity = i;
31            }
32        }
33        return minCity;
34    }
35}

Additional Notes

The time complexity of this solution is O(n^3) because we used Floyd-Warshall algorithm (which has a time complexity of O(n^3)) to compute the shortest distance between every pair of vertices. The space complexity is O(n^2), as we used a 2D array to store the minimum distances between the cities. Given that n is limited to 100 in the problem's constraints, this solution should be efficient enough.# Python Solution In Python, you can implement the solution in a function findTheCity. Here's how you can do it:

1
2python
3def findTheCity(n, edges, distanceThreshold):
4    INF = float('inf')
5    dist = [[INF]*n for _ in range(n)]
6    for i in range(n):
7        dist[i][i] = 0
8
9    for u, v, w in edges:
10        dist[u][v] = w
11        dist[v][u] = w
12
13    for k in range(n):
14        for i in range(n):
15            for j in range(n):
16                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
17
18    minCity = minOutgoing = None
19    for i in range(n):
20        outgoing = sum(d <= distanceThreshold for d in dist[i])
21        if minOutgoing is None or outgoing <= minOutgoing:
22            minCity, minOutgoing = i, outgoing
23
24    return minCity

JavaScript Solution

In JavaScript, you can define a function findTheCity to implement the solution.

1
2javascript
3function findTheCity(n, edges, distanceThreshold) {
4    let INF = Number.MAX_SAFE_INTEGER;
5    let dist = Array(n).fill().map(() => Array(n).fill(INF));
6
7    for (let i = 0; i < n; i++) {
8        dist[i][i] = 0;
9    }
10
11    for (let edge of edges) {
12        let [u, v, w] = edge;
13        dist[u][v] = w;
14        dist[v][u] = w;
15    }
16
17    for (let k = 0; k < n; k++) {
18        for (let i = 0; i < n; i++) {
19            for (let j = 0; j < n; j++) {
20                dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
21            }
22        }
23    }
24
25    let minCity = -1;
26    let minOutgoing = n;
27    for (let i = n - 1; i >= 0; i--) {
28        let outgoing = dist[i].reduce((count, d) => d <= distanceThreshold ? count + 1 : count, 0);
29        if (outgoing <= minOutgoing) {
30            minCity = i;
31            minOutgoing = outgoing;
32        }
33    }
34
35    return minCity;
36}

Now you have a clear picture of how to solve this problem using either Java, Python, or JavaScript. This solution uses the idea of the Floyd-Warshall algorithm to calculate the shortest path between each city, and then calculates the number of cities that are reachable within the distance threshold to find the city with the smallest number of reachable cities.


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫