Skip to main content

Find the City With the Smallest Number of Neighbors at a Threshold Distance - Solution & Explanation

MediumDynamic ProgrammingGraphShortest Path23 min readAsked at: Amazon, Microsoft, Meta +2
Practice this problem

Problem Statement

There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.

Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.

Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.

 

Example 1:

Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
Output: 3
Explanation: The figure above describes the graph. 
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.

Example 2:

Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
Output: 0
Explanation: The figure above describes the graph. 
The neighboring cities at a distanceThreshold = 2 for each city are:
City 0 -> [City 1] 
City 1 -> [City 0, City 4] 
City 2 -> [City 3, City 4] 
City 3 -> [City 2, City 4]
City 4 -> [City 1, City 2, City 3] 
The city 0 has 1 neighboring city at a distanceThreshold = 2.

 

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.

Approach Overview

Problem Overview: You are given n cities connected by weighted edges. A city can reach another if the shortest path distance is ≤ distanceThreshold. The goal is to return the city that can reach the smallest number of neighbors. If multiple cities tie, choose the one with the greatest index.

This is a classic all‑pairs shortest path problem. The key step is computing the minimum distance between every pair of cities, then counting how many are within the threshold for each city.

Approach 1: Floyd‑Warshall Algorithm (Time: O(n^3), Space: O(n^2))

Floyd‑Warshall computes shortest paths between every pair of nodes using dynamic programming. Initialize an n x n distance matrix with edge weights and set dist[i][i] = 0. Then iterate through each intermediate node k and update distances with dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]). After processing all intermediates, every cell contains the shortest path distance. Iterate through each city and count how many other cities have dist[i][j] ≤ distanceThreshold. Track the city with the smallest count, breaking ties by choosing the largest index. This method is straightforward and ideal when n is small (≤100), since the cubic runtime remains manageable.

This approach directly uses concepts from dynamic programming and graph shortest‑path relaxation.

Approach 2: Run Dijkstra from Every City (Time: O(n · (E log V)), Space: O(E + V))

Instead of computing all pairs at once, run Dijkstra’s algorithm starting from each city. Build an adjacency list for the graph, then use a min‑heap priority queue to repeatedly expand the smallest distance node. For each source city, compute shortest distances to all others while ignoring paths exceeding distanceThreshold. Count how many cities are reachable within the limit. Repeat this process for every city and maintain the minimum neighbor count with the required tie‑breaking rule.

This method scales better for sparse graphs where E is much smaller than n^2. It relies on standard shortest path techniques and a priority queue.

Recommended for interviews: Both approaches are acceptable. Floyd‑Warshall demonstrates clear understanding of all‑pairs shortest path and is often simpler to implement quickly. Running Dijkstra from each node shows stronger algorithmic awareness and performs better on sparse graphs. Mention both during discussion: the cubic dynamic programming solution first, then the repeated Dijkstra optimization.

Approach 1: Floyd-Warshall Algorithm

The Floyd-Warshall algorithm is a classical dynamic programming algorithm to solve the all-pairs shortest path problem. It works well for graphs that have both weighted and unweighted edges. The algorithm iteratively updates the distance matrix for each possible intermediate node and provides the shortest distances between any two nodes.

The algorithm has a time complexity of O(n^3) and a space complexity of O(n^2), making it suitable for graphs with up to 100 nodes as given in the problem constraints.

This solution implements the Floyd-Warshall algorithm to compute shortest paths between all city pairs. It then counts the number of neighboring cities within the given distance threshold for each city and identifies the city with the smallest number of reachable neighbors.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^3), where n is the number of cities.
Space Complexity: O(n^2) for storing the distance matrix.

Try this approach in the editor →

Approach 2: Dijkstra's Algorithm

Dijkstra's Algorithm can be employed to find the shortest path from one city to another in a graph with non-negative weights. We can utilize this algorithm to determine the shortest distance from every city to all other cities consecutively, assessing the count of reachable cities within the threshold afterward.

This solution leverages Dijkstra's algorithm separately on each city to compute all pairs shortest distance, and subsequently determines the smallest neighbors count within a specific threshold.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^2) for each node multiplied by n trips resulting in O(n^3).
Space Complexity: O(n^2) for graph storage.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

TypeScript

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Floyd-Warshall Algorithm

Time Complexity: O(n^3), where n is the number of cities.
Space Complexity: O(n^2) for storing the distance matrix.

Dijkstra's Algorithm

Time Complexity: O(n^2) for each node multiplied by n trips resulting in O(n^3).
Space Complexity: O(n^2) for graph storage.

Default Approach

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Floyd-Warshall AlgorithmO(n^3)O(n^2)Best when the graph is small and you want a simple all-pairs shortest path solution
Dijkstra from Each NodeO(n · (E log V))O(E + V)Preferred for sparse graphs where edges are far fewer than n^2

Video Solution

G-43. Find the City With the Smallest Number of Neighbours at a Threshold Distancetake U forward151,293 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Find the City With the Smallest Number of Neighbors at a Threshold Distance easy or hard?
The problem is rated Medium difficulty on LeetCode. The main challenge is recognizing it as a shortest‑path problem and choosing the right algorithm. Once you apply Floyd‑Warshall or Dijkstra correctly, the remaining logic is counting reachable cities and applying the tie‑breaking rule.
Find the City With the Smallest Number of Neighbors at a Threshold Distance Python/Java solution
Most solutions implement Floyd‑Warshall or repeated Dijkstra. Python typically uses lists for the distance matrix or adjacency list and the heapq module for the priority queue. Java solutions often use arrays for distances and PriorityQueue for Dijkstra's algorithm.
How to solve Find the City With the Smallest Number of Neighbors at a Threshold Distance in O(n^3)?
Use the Floyd‑Warshall algorithm. Initialize a distance matrix with edge weights and repeatedly relax distances through intermediate nodes using dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]). After computing all shortest paths, count how many cities each city can reach within the distance threshold and select the city with the smallest count.
What is the best approach for Find the City With the Smallest Number of Neighbors at a Threshold Distance?
Two common approaches solve this problem: Floyd‑Warshall and running Dijkstra from every node. Floyd‑Warshall computes all‑pairs shortest paths in O(n^3) time and is simple to implement. Repeated Dijkstra runs in O(n · (E log V)) and performs better for sparse graphs. Interviewers often accept either solution.
Is Find the City With the Smallest Number of Neighbors at a Threshold Distance asked at Google/Amazon/Meta?
Graph shortest‑path problems similar to this one frequently appear in interviews at companies like Amazon, Google, and Meta. The question tests understanding of graph representations, shortest path algorithms such as Dijkstra, and all‑pairs techniques like Floyd‑Warshall.
What data structure is used in Find the City With the Smallest Number of Neighbors at a Threshold Distance?
The problem uses graph data structures. Floyd‑Warshall relies on a 2D distance matrix to store shortest paths between all city pairs. The Dijkstra approach uses an adjacency list representation of the graph along with a min‑heap priority queue for efficient shortest path expansion.
What is the time complexity of Find the City With the Smallest Number of Neighbors at a Threshold Distance?
The Floyd‑Warshall solution runs in O(n^3) time with O(n^2) space because it updates distances between every pair of cities through each intermediate node. Running Dijkstra from each city has time complexity O(n · (E log V)) with O(E + V) space using an adjacency list and priority queue.

Ready to solve this problem?

Practice Find the City With the Smallest Number of Neighbors at a Threshold Distance with our built-in code editor and test cases.

Practice on FleetCode