#2858
Minimum Edge Reversals So Every Node Is Reachable
HardDynamic ProgrammingDepth-First SearchBreadth-First SearchGraph TheoryGraph TraversalDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach utilizes a tree dynamic programming strategy, treating the graph as a tree and calculating reversals in a bottom-up manner. This allows us to efficiently compute the minimum reversals needed for each node to reach all others.
⚙️
Algorithm
3 steps- 1Step 1: Build a directed graph from the edges, noting the direction of each edge.
- 2Step 2: Use a DFS to calculate the minimum reversals needed for each node by considering its children.
- 3Step 3: Store the results in an array and return it.
solution.py20 lines
1# Full working Python code
2from collections import defaultdict
3
4def minEdgeReversals(n, edges):
5 graph = defaultdict(list)
6 for u, v in edges:
7 graph[u].append((v, 0)) # original direction
8 graph[v].append((u, 1)) # reversed direction
9
10 def dfs(node, parent):
11 total_reversals = 0
12 for neighbor, cost in graph[node]:
13 if neighbor != parent:
14 total_reversals += cost + dfs(neighbor, node)
15 return total_reversals
16
17 result = [0] * n
18 for i in range(n):
19 result[i] = dfs(i, -1)
20 return resultℹ
Complexity note: This complexity is due to the single DFS traversal through the graph, where each node and edge is processed once.
- 1Understanding the direction of edges is crucial for calculating reversals.
- 2Using DFS allows us to explore the graph efficiently and compute reversals in a structured manner.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.