Minimum Score of a Path Between Two Cities — LeetCode 2492 Python Solution

MediumDepth-First SearchBreadth-First SearchUnion FindGraph
Problem
#2492
Pattern
Union-Find
Reading time
3 min

The 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.

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n + m), where n and m are the number of nodes and edges, respectively
SpaceO(V) auxiliary

Pattern: Union-Find

Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 2492. Minimum Score of a Path Between Two Cities is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.

The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2492. Minimum Score of a Path Between Two Cities?
LeetCode 2492. Minimum Score of a Path Between Two Cities is rated Medium on LeetCode.
What is the time complexity of LeetCode 2492. Minimum Score of a Path Between Two Cities?
The Python solution on this page runs in O(n + m), where n and m are the number of nodes and edges, respectively.
What is the space complexity of LeetCode 2492. Minimum Score of a Path Between Two Cities?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 2492. Minimum Score of a Path Between Two Cities cover?
LeetCode 2492. Minimum Score of a Path Between Two Cities is tagged Depth-First Search, Breadth-First Search, Union Find and Graph on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview