#2492
Minimum Score of a Path Between Two Cities
MediumDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryGraph TraversalBreadth-First SearchDepth-First Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + m)Space O(n)
The optimal solution leverages a graph traversal technique (like BFS) to find the minimum score efficiently. Instead of exploring all paths, we only need to find the connected component between cities 1 and n and track the minimum edge weight.
⚙️
Algorithm
3 steps- 1Step 1: Build the graph using an adjacency list from the roads data.
- 2Step 2: Use Breadth-First Search (BFS) starting from city 1 to explore all reachable cities.
- 3Step 3: During the BFS, track the minimum distance of the roads used to reach city n.
solution.py20 lines
1def minScore(n, roads):
2 from collections import defaultdict, deque
3 graph = defaultdict(list)
4 for a, b, d in roads:
5 graph[a].append((b, d))
6 graph[b].append((a, d))
7
8 min_distance = float('inf')
9 queue = deque([1])
10 visited = set([1])
11
12 while queue:
13 city = queue.popleft()
14 for neighbor, distance in graph[city]:
15 min_distance = min(min_distance, distance)
16 if neighbor not in visited:
17 visited.add(neighbor)
18 queue.append(neighbor)
19
20 return min_distanceℹ
Complexity note: The time complexity is O(n + m) where n is the number of cities and m is the number of roads, as we traverse each node and edge once during BFS.
- 1The minimum score is determined by the weakest link in the path, which is the minimum distance road.
- 2Using BFS allows us to efficiently explore the graph without redundant paths.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.