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

grid47
grid47
Exploring patterns and algorithms
Jun 26, 2024 8 min read

Given a set of cities connected by weighted edges, find the city with the least number of reachable cities under a distance threshold. If multiple cities have the same number of reachable cities, return the one with the greatest index.
Problem
Approach
Steps
Complexity
Input: You are given an integer `n`, representing the number of cities. You are also given a list of edges where each edge is an array `[fromi, toi, weighti]`, representing a bidirectional edge between cities `fromi` and `toi` with weight `weighti`. Additionally, you are given an integer `distanceThreshold` that limits the maximum distance for considering a reachable city.
Example: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
Constraints:
• 2 <= n <= 100
• 1 <= edges.length <= n * (n - 1) / 2
• edges[i].length == 3
• 0 <= fromi < toi < n
• 1 <= weighti, distanceThreshold <= 10^4
• All pairs (fromi, toi) are distinct.
Output: Return the city with the smallest number of cities reachable within the `distanceThreshold`. If there are multiple such cities, return the city with the highest index.
Example: For `n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4`, the output will be `City 3`.
Constraints:
Goal: Find the city with the least number of reachable cities within the distance threshold and return the one with the greatest index in case of ties.
Steps:
• 1. Represent the cities and edges using an adjacency matrix or a graph.
• 2. Implement a shortest path algorithm (like Floyd-Warshall) to compute the minimum distances between all pairs of cities.
• 3. For each city, count the number of cities that are reachable within the distance threshold.
• 4. Keep track of the city with the fewest reachable cities, and in case of a tie, return the city with the largest index.
Goal: The problem imposes the following constraints on the inputs:
Steps:
• 2 <= n <= 100
• 1 <= edges.length <= n * (n - 1) / 2
• edges[i].length == 3
• 0 <= fromi < toi < n
• 1 <= weighti, distanceThreshold <= 10^4
• All pairs (fromi, toi) are distinct.
Assumptions:
• The graph is undirected.
• The weights on edges are positive integers.
• The graph is connected enough for a reasonable number of cities to be reachable from any city.
Input: Example 1: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
Explanation: City 3 has the least number of reachable cities (2 cities), and has the highest index, so the answer is City 3.

Input: Example 2: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
Explanation: City 0 has the fewest reachable cities (only 1), so it is the answer.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus