#3108
Minimum Cost Walk in Weighted Graph
HardArrayBit ManipulationUnion-FindGraph TheoryDisjoint Set Union (Union-Find)Graph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Using the Disjoint Set Union (DSU) allows us to efficiently group connected components. We can then determine if two vertices are connected and calculate the minimum cost of the walk based on the weights of the edges in the component.
⚙️
Algorithm
3 steps- 1Step 1: Create a Disjoint Set Union (DSU) to group connected components based on the edges.
- 2Step 2: For each edge, union the two vertices and keep track of the minimum weight in each component.
- 3Step 3: For each query, check if the two vertices belong to the same component using DSU. If they do, return the minimum weight; otherwise, return -1.
solution.py39 lines
1# Full working Python code
2class DSU:
3 def __init__(self, n):
4 self.parent = list(range(n))
5 self.rank = [0] * n
6 self.min_weight = [float('inf')] * n
7
8 def find(self, u):
9 if self.parent[u] != u:
10 self.parent[u] = self.find(self.parent[u])
11 return self.parent[u]
12
13 def union(self, u, v, weight):
14 root_u = self.find(u)
15 root_v = self.find(v)
16 if root_u != root_v:
17 if self.rank[root_u] > self.rank[root_v]:
18 self.parent[root_v] = root_u
19 self.min_weight[root_u] = min(self.min_weight[root_u], self.min_weight[root_v], weight)
20 elif self.rank[root_u] < self.rank[root_v]:
21 self.parent[root_u] = root_v
22 self.min_weight[root_v] = min(self.min_weight[root_u], self.min_weight[root_v], weight)
23 else:
24 self.parent[root_v] = root_u
25 self.min_weight[root_u] = min(self.min_weight[root_u], self.min_weight[root_v], weight)
26 self.rank[root_u] += 1
27
28
29def min_cost_walk(n, edges, queries):
30 dsu = DSU(n)
31 for u, v, w in edges:
32 dsu.union(u, v, w)
33 results = []
34 for s, t in queries:
35 if dsu.find(s) == dsu.find(t):
36 results.append(dsu.min_weight[dsu.find(s)])
37 else:
38 results.append(-1)
39 return resultsℹ
Complexity note: The time complexity is O(n log n) due to the union-find operations, which are nearly constant time due to path compression and union by rank.
- 1Understanding the bitwise AND operation is crucial for determining the cost of walks.
- 2Using a Disjoint Set Union (DSU) can significantly optimize the process of finding connected components.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.