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.
You are given an integer n and a 2D integer array edges, where edges[i] = [ui, vi] represents a directed edge going from node ui to node vi.
An edge reversal changes the direction of an edge, i.e., a directed edge going from node ui to node vi becomes a directed edge going from node vi to node ui.
For every node i in the range [0, n - 1], your task is to independently calculate the minimum number of edge reversals required so it is possible to reach any other node starting from node i through a sequence of directed edges.
Return an integer array answer, where answer[i] is theminimum number of edge reversals required so it is possible to reach any other node starting from node i through a sequence of directed edges.
Example 1:
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.
Example 2:
Input: n = 3, edges = [[1,2],[2,0]]
Output: [2,0,1]
Explanation: The image above shows the graph formed by the edges.
For node 0: after reversing the edges [2,0] and [1,2], it is possible to reach any other node starting from node 0.
So, answer[0] = 2.
For node 1: it is already possible to reach any other node starting from node 1.
So, answer[1] = 0.
For node 2: after reversing the edge [1, 2], it is possible to reach any other node starting from node 2.
So, answer[2] = 1.
Constraints:
2 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ui == edges[i][0] < n
0 <= vi == edges[i][1] < n
ui != vi
The input is generated such that if the edges were bi-directional, the graph would be a tree.
Problem summary: 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. You are given an integer n and a 2D integer array edges, where edges[i] = [ui, vi] represents a directed edge going from node ui to node vi. An edge reversal changes the direction of an edge, i.e., a directed edge going from node ui to node vi becomes a directed edge going from node vi to node ui. For every node i in the range [0, n - 1], your task is to independently calculate the minimum number of edge reversals required so it is possible to reach any other node starting from node i through a sequence of directed edges. Return an integer array answer, where answer[i] is the minimum number of edge reversals required so it is possible to reach any other node starting from node i through a sequence of directed edges.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
4
[[2,0],[2,1],[1,3]]
Example 2
3
[[1,2],[2,0]]
Related Problems
Reorder Routes to Make All Paths Lead to the City Zero (reorder-routes-to-make-all-paths-lead-to-the-city-zero)
Step 02
Core Insight
What unlocks the optimal approach
The problem can be solved using tree DP.
Using node <code>0</code> as the root, let <code>dp[x]</code> be the minimum number of edge reversals so node <code>x</code> can reach every node in its subtree.
Using a DFS traversing the edges bidirectionally, we can compute <code>dp</code>.<br /> <code>dp[x] = dp[y] +</code> (<code>1</code> if the edge between <code>x</code> and <code>y</code> is going from <code>y</code> to <code>x</code>; <code>0</code> otherwise), where <code>x</code> is the parent of <code>y</code>.
Let <code>answer[x]</code> be the minimum number of edge reversals so it is possible to reach any other node starting from node <code>x</code>.
Using another DFS starting from node <code>0</code> and traversing the edges bidirectionally, we can compute <code>answer</code>.<br /> <code>answer[0] = dp[0]</code><br /> <code>answer[y] = answer[x] +</code> (<code>1</code> if the edge between <code>x</code> and <code>y</code> is going from <code>x</code> to <code>y</code>; <code>-1</code> otherwise), where <code>x</code> is the parent of <code>y</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2858: Minimum Edge Reversals So Every Node Is Reachable
class Solution {
private List<int[]>[] g;
private int[] ans;
public int[] minEdgeReversals(int n, int[][] edges) {
ans = new int[n];
g = new List[n];
Arrays.setAll(g, i -> new ArrayList<>());
for (var e : edges) {
int x = e[0], y = e[1];
g[x].add(new int[] {y, 1});
g[y].add(new int[] {x, -1});
}
dfs(0, -1);
dfs2(0, -1);
return ans;
}
private void dfs(int i, int fa) {
for (var ne : g[i]) {
int j = ne[0], k = ne[1];
if (j != fa) {
ans[0] += k < 0 ? 1 : 0;
dfs(j, i);
}
}
}
private void dfs2(int i, int fa) {
for (var ne : g[i]) {
int j = ne[0], k = ne[1];
if (j != fa) {
ans[j] = ans[i] + k;
dfs2(j, i);
}
}
}
}
// Accepted solution for LeetCode #2858: Minimum Edge Reversals So Every Node Is Reachable
func minEdgeReversals(n int, edges [][]int) []int {
g := make([][][2]int, n)
for _, e := range edges {
x, y := e[0], e[1]
g[x] = append(g[x], [2]int{y, 1})
g[y] = append(g[y], [2]int{x, -1})
}
ans := make([]int, n)
var dfs func(int, int)
var dfs2 func(int, int)
dfs = func(i, fa int) {
for _, ne := range g[i] {
j, k := ne[0], ne[1]
if j != fa {
if k < 0 {
ans[0]++
}
dfs(j, i)
}
}
}
dfs2 = func(i, fa int) {
for _, ne := range g[i] {
j, k := ne[0], ne[1]
if j != fa {
ans[j] = ans[i] + k
dfs2(j, i)
}
}
}
dfs(0, -1)
dfs2(0, -1)
return ans
}
# Accepted solution for LeetCode #2858: Minimum Edge Reversals So Every Node Is Reachable
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
// Accepted solution for LeetCode #2858: Minimum Edge Reversals So Every Node Is Reachable
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2858: Minimum Edge Reversals So Every Node Is Reachable
// class Solution {
// private List<int[]>[] g;
// private int[] ans;
//
// public int[] minEdgeReversals(int n, int[][] edges) {
// ans = new int[n];
// g = new List[n];
// Arrays.setAll(g, i -> new ArrayList<>());
// for (var e : edges) {
// int x = e[0], y = e[1];
// g[x].add(new int[] {y, 1});
// g[y].add(new int[] {x, -1});
// }
// dfs(0, -1);
// dfs2(0, -1);
// return ans;
// }
//
// private void dfs(int i, int fa) {
// for (var ne : g[i]) {
// int j = ne[0], k = ne[1];
// if (j != fa) {
// ans[0] += k < 0 ? 1 : 0;
// dfs(j, i);
// }
// }
// }
//
// private void dfs2(int i, int fa) {
// for (var ne : g[i]) {
// int j = ne[0], k = ne[1];
// if (j != fa) {
// ans[j] = ans[i] + k;
// dfs2(j, i);
// }
// }
// }
// }
// Accepted solution for LeetCode #2858: Minimum Edge Reversals So Every Node Is Reachable
function minEdgeReversals(n: number, edges: number[][]): number[] {
const g: number[][][] = Array.from({ length: n }, () => []);
for (const [x, y] of edges) {
g[x].push([y, 1]);
g[y].push([x, -1]);
}
const ans: number[] = Array(n).fill(0);
const dfs = (i: number, fa: number) => {
for (const [j, k] of g[i]) {
if (j !== fa) {
ans[0] += k < 0 ? 1 : 0;
dfs(j, i);
}
}
};
const dfs2 = (i: number, fa: number) => {
for (const [j, k] of g[i]) {
if (j !== fa) {
ans[j] = ans[i] + k;
dfs2(j, i);
}
}
};
dfs(0, -1);
dfs2(0, -1);
return ans;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.