Minimum Score of a Path Between Two Cities - Problem

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 equal to distancei. The cities graph is not necessarily connected.

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 cities 1 and n.

Note:

  • A path is a sequence of roads between two cities.
  • It is allowed for a path to contain the same road multiple times, and you can visit cities 1 and n multiple times along the path.
  • The test cases are generated such that there is at least one path between 1 and n.

Input & Output

Example 1 — Basic Path
$ Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]
Output: 5
💡 Note: The path from city 1 to 4: 1 → 4 has minimum road distance 7. But we can go 1 → 2 → 4 with minimum road distance min(9,5) = 5, which is better.
Example 2 — Direct Connection
$ Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]]
Output: 2
💡 Note: Path 1 → 2 → 1 → 3 → 4 uses roads with distances [2,2,4,7], minimum is 2.

Constraints

  • 2 ≤ n ≤ 105
  • 1 ≤ roads.length ≤ 105
  • roads[i].length == 3
  • 1 ≤ ai, bi ≤ n
  • ai ≠ bi
  • 1 ≤ distancei ≤ 104

Visualization

Tap to expand
Minimum Score of a Path Between Two Cities INPUT 1 2 3 4 9 6 5 7 n = 4 roads = [ [1,2,9], [2,3,6], [2,4,5], [1,4,7] ] ALGORITHM (DFS) 1 Start DFS from node 1 Track visited nodes 2 Explore all edges In connected component 3 Track minimum edge Update min score found 4 Return minimum Smallest edge weight DFS Traversal: Visit 1: edges 9, 7 Visit 2: edges 9, 6, 5 Visit 3: edge 6 Visit 4: edges 5, 7 Min found: 5 FINAL RESULT 1 2 3 4 5 Output: 5 OK - Minimum score from city 1 to city 4 Edge 2--4 has weight 5 Key Insight: The minimum score is the smallest edge weight in the entire connected component containing nodes 1 and n. Any edge in the component can be traversed multiple times, so we just need to find the minimum edge reachable from node 1. TutorialsPoint - Minimum Score of a Path Between Two Cities | DFS Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
28.5K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen