Leetcode #2858: Minimum Edge Reversals So Every Node Is Reachable
In this guide, we solve Leetcode #2858 Minimum Edge Reversals So Every Node Is Reachable in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
There is a simple directed graph with n nodes labeled from 0 to n - 1. The graph would form a tree if its edges were bi-directional.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Depth-First Search, Breadth-First Search, Graph, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: n = 4, edges = [[2,0],[2,1],[1,3]]
Output: [1,1,0,2]
Explanation: The image above shows the graph formed by the edges.
For node 0: after reversing the edge [2,0], it is possible to reach any other node starting from node 0.
So, answer[0] = 1.
For node 1: after reversing the edge [2,1], it is possible to reach any other node starting from node 1.
So, answer[1] = 1.
For node 2: it is already possible to reach any other node starting from node 2.
So, answer[2] = 0.
For node 3: after reversing the edges [1,3] and [2,1], it is possible to reach any other node starting from node 3.
So, answer[3] = 2.
Python Solution
class Solution:
def minEdgeReversals(self, n: int, edges: List[List[int]]) -> List[int]:
ans = [0] * n
g = [[] for _ in range(n)]
for x, y in edges:
g[x].append((y, 1))
g[y].append((x, -1))
def dfs(i: int, fa: int):
for j, k in g[i]:
if j != fa:
ans[0] += int(k < 0)
dfs(j, i)
dfs(0, -1)
def dfs2(i: int, fa: int):
for j, k in g[i]:
if j != fa:
ans[j] = ans[i] + k
dfs2(j, i)
dfs2(0, -1)
return ans
Complexity
The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.