Minimum Edge Reversals So Every Node Is Reachable - Problem

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.

Input & Output

Example 1 — Linear Chain
$ Input: n = 6, edges = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: [3,4,5,4,2,3]
💡 Note: For node 0 as root: need to reverse edges [3,1], [3,2], [5,4] = 3 reversals. For other nodes, use re-rooting to calculate efficiently.
Example 2 — Simple Tree
$ Input: n = 3, edges = [[0,1],[1,2]]
Output: [0,1,2]
💡 Note: From node 0: no reversals needed. From node 1: reverse [0,1] = 1 reversal. From node 2: reverse [0,1] and [1,2] = 2 reversals.
Example 3 — Star Configuration
$ Input: n = 4, edges = [[1,0],[2,0],[3,0]]
Output: [0,1,1,1]
💡 Note: From node 0: all edges point to 0, no reversals needed. From any other node: need 1 reversal to reach node 0, then can reach others.

Constraints

  • 2 ≤ n ≤ 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 ≤ ui, vi ≤ n - 1
  • ui != vi
  • The input is guaranteed to form a tree when edges are bi-directional

Visualization

Tap to expand
Minimum Edge Reversals ProblemInput: Directed Tree012Process: Calculate for Each RootRoot at 0:0 reversalsneededOutput: Reversal Counts[0, 1, 2]Start 0Start 1Start 2Tree re-rooting gives O(n) solutionRoot at 0: needs 0 reversals | Root at 1: needs 1 reversal | Root at 2: needs 2 reversals
Understanding the Visualization
1
Input Graph
Directed tree with edges that can be reversed
2
Calculate Reversals
For each node, find minimum reversals to reach all others
3
Output Array
Return array of minimum reversals for each starting node
Key Takeaway
🎯 Key Insight: Tree re-rooting allows calculating all answers in O(n) time instead of O(n²)
Asked in
Google 15 Facebook 8 Microsoft 12
12.5K Views
Medium Frequency
~35 min Avg. Time
187 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen