Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using union-find strategy.
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:
1 and n multiple times along the path.1 and n.Example 1:
Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]] Output: 5 Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5. It can be shown that no other path has less score.
Example 2:
Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]] Output: 2 Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2.
Constraints:
2 <= n <= 1051 <= roads.length <= 105roads[i].length == 31 <= ai, bi <= nai != bi1 <= distancei <= 1041 and n.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Union-Find
4 [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]
4 [[1,2,2],[1,3,4],[3,4,7]]
checking-existence-of-edge-length-limited-paths)checking-existence-of-edge-length-limited-paths-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2492: Minimum Score of a Path Between Two Cities
class Solution {
private List<int[]>[] g;
private boolean[] vis;
private int ans = 1 << 30;
public int minScore(int n, int[][] roads) {
g = new List[n];
vis = new boolean[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : roads) {
int a = e[0] - 1, b = e[1] - 1, d = e[2];
g[a].add(new int[] {b, d});
g[b].add(new int[] {a, d});
}
dfs(0);
return ans;
}
private void dfs(int i) {
for (var nxt : g[i]) {
int j = nxt[0], d = nxt[1];
ans = Math.min(ans, d);
if (!vis[j]) {
vis[j] = true;
dfs(j);
}
}
}
}
// Accepted solution for LeetCode #2492: Minimum Score of a Path Between Two Cities
func minScore(n int, roads [][]int) int {
type pair struct{ i, v int }
g := make([][]pair, n)
for _, e := range roads {
a, b, d := e[0]-1, e[1]-1, e[2]
g[a] = append(g[a], pair{b, d})
g[b] = append(g[b], pair{a, d})
}
vis := make([]bool, n)
ans := 1 << 30
var dfs func(int)
dfs = func(i int) {
for _, nxt := range g[i] {
j, d := nxt.i, nxt.v
ans = min(ans, d)
if !vis[j] {
vis[j] = true
dfs(j)
}
}
}
dfs(0)
return ans
}
# Accepted solution for LeetCode #2492: Minimum Score of a Path Between Two Cities
class Solution:
def minScore(self, n: int, roads: List[List[int]]) -> int:
def dfs(i):
nonlocal ans
for j, d in g[i]:
ans = min(ans, d)
if not vis[j]:
vis[j] = True
dfs(j)
g = defaultdict(list)
for a, b, d in roads:
g[a].append((b, d))
g[b].append((a, d))
vis = [False] * (n + 1)
ans = inf
dfs(1)
return ans
// Accepted solution for LeetCode #2492: Minimum Score of a Path Between Two Cities
impl Solution {
fn dfs(i: usize, mut ans: i32, g: &Vec<Vec<(usize, i32)>>, vis: &mut Vec<bool>) -> i32 {
if vis[i] {
return ans;
}
vis[i] = true;
for (j, v) in g[i].iter() {
ans = ans.min(*v.min(&Self::dfs(*j, ans, g, vis)));
}
ans
}
pub fn min_score(n: i32, roads: Vec<Vec<i32>>) -> i32 {
let n = n as usize;
let mut vis = vec![false; n + 1];
let mut g = vec![Vec::new(); n + 1];
for road in roads.iter() {
let a = road[0] as usize;
let b = road[1] as usize;
let v = road[2];
g[a].push((b, v));
g[b].push((a, v));
}
Self::dfs(1, i32::MAX, &g, &mut vis)
}
}
// Accepted solution for LeetCode #2492: Minimum Score of a Path Between Two Cities
function minScore(n: number, roads: number[][]): number {
const vis = new Array(n + 1).fill(false);
const g = Array.from({ length: n + 1 }, () => []);
for (const [a, b, v] of roads) {
g[a].push([b, v]);
g[b].push([a, v]);
}
let ans = Infinity;
const dfs = (i: number) => {
if (vis[i]) {
return;
}
vis[i] = true;
for (const [j, v] of g[i]) {
ans = Math.min(ans, v);
dfs(j);
}
};
dfs(1);
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Track components with a list or adjacency matrix. Each union operation may need to update all n elements’ component labels, giving O(n) per union. For n union operations total: O(n²). Find is O(1) with direct lookup, but union dominates.
With path compression and union by rank, each find/union operation takes O(α(n)) amortized time, where α is the inverse Ackermann function — effectively constant. Space is O(n) for the parent and rank arrays. For m operations on n elements: O(m × α(n)) total.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.