Minimum Score of a Path Between Two Cities

Minimum Score of a Path Between Two Cities

Leetcode Daily Challenge (22nd March, 2023)

Problem Statement:-

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] = [a<sub>i</sub>, b<sub>i</sub>, distance<sub>i</sub>] indicates that there is a bidirectional road between cities a<sub>i</sub> and b<sub>i</sub> with a distance equal to distance<sub>i</sub>. 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.

Link: https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities/description/

Problem Explanation with examples:-

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 <= 10<sup>5</sup>

  • 1 <= roads.length <= 10<sup>5</sup>

  • roads[i].length == 3

  • 1 <= a<sub>i</sub>, b<sub>i</sub> <= n

  • a<sub>i</sub> != b<sub>i</sub>

  • 1 <= distance<sub>i</sub> <= 10<sup>4</sup>

  • There are no repeated edges.

  • There is at least one path between 1 and n.

Intuition:-

  • We simply need to find the minimum weight edge in the graph which can connect from node 1 to any other node which in turn can connect to the Nth node.

  • We can use BFS to find the minimum weight edge.

  • We can use a queue to store the nodes to be visited and a set to store the visited nodes.

  • We can start with node 1 and add it to the queue and visited set.

  • We can pop the first element from the queue and iterate through all the adjacent nodes of the popped node.

  • If the adjacent node is not visited, then we can add it to the queue and visited set.

  • We can also find the minimum weight edge by comparing the weight of the current edge with the minimum weight edge found so far.

  • Finally, we can return the minimum weight edge.

  • DFS can also be used to find the minimum weight edge.

Solution:-

  • Initialize a graph to store the edges and weights of the graph.

  • Iterate through the edges and add the edges and weights to the graph.

  • Initialize a variable mn to infinity and a set visited to store the visited nodes.

  • Initialize a queue q to store the nodes to be visited.

  • Add node 1 to the queue.

  • While the queue is not empty, we can pop the first element from the queue and iterate through all the adjacent nodes of the popped node.

  • If the adjacent node is not visited, then we can add it to the queue and visited set.

  • We can also find the minimum weight edge by comparing the weight of the current edge with the minimum weight edge found so far.

  • Finally, we can return the minimum weight edge.

Code:-

JAVA Solution

class Solution {
    public int minScore(int n, int[][] roads) {
        Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();

        for (int[] road : roads) {
            int u = road[0];
            int v = road[1];
            int w = road[2];

            if (!graph.containsKey(u)) {
                graph.put(u, new HashMap<>());
            }
            if (!graph.containsKey(v)) {
                graph.put(v, new HashMap<>());
            }

            graph.get(u).put(v, w);
            graph.get(v).put(u, w);
        }

        int mn = Integer.MAX_VALUE;
        Set<Integer> visited = new HashSet<>();
        Queue<Integer> q = new LinkedList<>();
        q.add(1);

        while (!q.isEmpty()) {
            int node = q.poll();

            for (Map.Entry<Integer, Integer> entry : graph.get(node).entrySet()) {
                int adj = entry.getKey();
                int wt = entry.getValue();

                if (!visited.contains(adj)) {
                    q.add(adj);
                    visited.add(adj);
                }
                mn = Math.min(mn, wt);
            }
        }

        return mn;
    }
}

Python Solution

class Solution:
    def minScore(self, n: int, roads: List[List[int]]) -> int:
        graph = defaultdict(dict)

        for u,v,w in roads:
            graph[u][v] = graph[v][u] = w

        mn = float('inf')
        visited = set()
        q = [1]

        while q:
            node = q.pop(0)

            for adj,wt in graph[node].items():
                if adj not in visited:
                    q.append(adj)
                    visited.add(adj)
                mn = min(mn,wt)

        return mn

Complexity Analysis:-

TIME:-

Time complexity is O(N+M), where N is the number of nodes and M is the number of edges in the graph. In the while loop, we visit each node in the graph at most once. For each node, we iterate through its adjacent nodes and update the minimum weight. Since we visit each edge at most twice (once for each endpoint), the time complexity is O(N+M).

SPACE:-

Space complexity is O(N+M) because we store the graph using a map data structure. We use a map to store the graph, so the space complexity is also O(N+M). The set and queue data structures used for bookkeeping have a space complexity of O(N).

References:-

Connect with me:-

Did you find this article valuable?

Support Leeting-LCS by becoming a sponsor. Any amount is appreciated!