Minimum Score of a Path Between Two Cities (LeetCode 2492): Solution and Explanation
Cities 1 to n are joined by two-way weighted roads. The score of a path is its cheapest road, and paths may reuse roads. Find the smallest score of any path from city 1 to city n.
Intuition
It looks like a shortest path problem, but it is not. The score only cares about the single cheapest road on the path, and the path is allowed to repeat roads and cities.
That freedom means a path from 1 can walk out to any road in its component, cross it, walk back and then head to n. Every road reachable from city 1 can be put on some valid path.
So the answer is the minimum distance over all roads in the connected component of city 1. Roads in other components can never be used, however cheap they are.
Approach: BFS over the component of city 1
- Build adjacency lists that store the neighbor and the road distance for both directions.
- Start a BFS from city 1 with best set to infinity.
- For every road leaving a popped city, set best = min(best, distance), and enqueue the neighbor if it is new.
- When the queue empties, every road of the component has been seen. Return best.
Step-by-step example
n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]
- Pop city 1. Its roads have distances 9 (to 2) and 7 (to 4), so best = 7. Enqueue 2 and 4.
- Pop city 2. Its roads have distances 9, 6 and 5, so best drops to 6 and then to 5. Enqueue 3.
- Pop city 4. Roads 5 and 7 do not beat 5.
- Pop city 3. Road 6 does not beat 5.
- The queue is empty. Return 5, for example via the path 1 -> 2 -> 4.
Code: Python, Java, C++
1class Solution:
2 def minScore(self, n: int, roads: List[List[int]]) -> int:
3 adj = [[] for _ in range(n + 1)]
4 for a, b, d in roads:
5 adj[a].append((b, d))
6 adj[b].append((a, d))
7 seen = [False] * (n + 1)
8 seen[1] = True
9 queue = deque([1])
10 best = float('inf')
11 while queue:
12 u = queue.popleft()
13 for v, d in adj[u]:
14 best = min(best, d)
15 if not seen[v]:
16 seen[v] = True
17 queue.append(v)
18 return best1class Solution {
2 public int minScore(int n, int[][] roads) {
3 List<List<int[]>> adj = new ArrayList<>();
4 for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());
5 for (int[] r : roads) {
6 adj.get(r[0]).add(new int[]{r[1], r[2]});
7 adj.get(r[1]).add(new int[]{r[0], r[2]});
8 }
9 boolean[] seen = new boolean[n + 1];
10 seen[1] = true;
11 Deque<Integer> queue = new ArrayDeque<>();
12 queue.offer(1);
13 int best = Integer.MAX_VALUE;
14 while (!queue.isEmpty()) {
15 int u = queue.poll();
16 for (int[] e : adj.get(u)) {
17 best = Math.min(best, e[1]);
18 if (!seen[e[0]]) {
19 seen[e[0]] = true;
20 queue.offer(e[0]);
21 }
22 }
23 }
24 return best;
25 }
26}1class Solution {
2public:
3 int minScore(int n, vector<vector<int>>& roads) {
4 vector<vector<pair<int, int>>> adj(n + 1);
5 for (auto& r : roads) {
6 adj[r[0]].push_back({r[1], r[2]});
7 adj[r[1]].push_back({r[0], r[2]});
8 }
9 vector<bool> seen(n + 1, false);
10 seen[1] = true;
11 queue<int> q;
12 q.push(1);
13 int best = INT_MAX;
14 while (!q.empty()) {
15 int u = q.front();
16 q.pop();
17 for (auto& [v, d] : adj[u]) {
18 best = min(best, d);
19 if (!seen[v]) {
20 seen[v] = true;
21 q.push(v);
22 }
23 }
24 }
25 return best;
26 }
27};Time and space complexity
O(n + m)
Each city is enqueued at most once and each road is examined twice, once from each end.
O(n + m)
The adjacency lists hold every road twice, plus the seen array and the queue.
Other approaches
Union-find (time O((n + m) * a(n)), space O(n))
Union the endpoints of every road, then scan the roads again and take the minimum distance among those whose endpoint shares a root with city 1.
Recursive DFS (time O(n + m), space O(n + m))
Same idea with a depth-first walk. It works, but with up to 100,000 cities the recursion can overflow the stack in some languages, so an explicit stack or queue is safer.
Common mistakes
- Running Dijkstra or a shortest path search. The score is a minimum over roads, not a sum, and roads may be reused.
- Taking the minimum over all roads in the input. A cheap road in a different component is unreachable and must be ignored.
- Only updating best when the neighbor is unvisited. A road between two already seen cities can still be the cheapest one.
- Forgetting that cities are numbered from 1, which needs arrays of size n + 1.
Frequently asked questions
Why can a path use a road that is not between 1 and n?
Paths may repeat cities and roads. You can walk from 1 to that road, cross it, walk back the same way and then continue to n, so it lies on a valid path.
Do I need to reach city n during the search?
No. The problem guarantees that 1 and n are connected, so they are in the same component and exploring from 1 alone is enough.
Why does the BFS look at every road, including ones that lead back to seen cities?
The minimum is over roads, not cities. Checking every road out of every popped city guarantees each road in the component is compared at least once.