Minimum Score of a Path Between Two Cities
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Union Find.
Minimum Score of a Path Between Two Cities
You are given a positive integer
n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [ai, bi, distancei] indicates that there is a bidirectional road between cities ai and bi with a distance distancei. The score of a path between two cities is defined as the minimum distance of a road in this path. Return the minimum possible score of a path between city 1 and city n.Insight
If cities
1 and n are connected, you can traverse any road in their connected component multiple times. Thus, the answer is simply the minimum weight road in the entire component containing city 1.Examples
Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]
Output: 5
Approach 1
Level I: DFS (Component Traversal)
Intuition
Since we can traverse any road in a connected component multiple times, the path score is simply the minimum weight of any road in the entire component that contains city 1 (and thus city n, if reachable). Use DFS to traverse the component and track the minimum weight encountered.
⏱ O(V + E).💾 O(V + E).
Approach 2
Level III: Union-Find (Component Min Edge)
Intuition
Use DSU to maintain connected components and store the minimum edge weight seen so far for each component root.
⏱ O(E \cdot \alpha(N)).💾 O(N).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.