Minimum Edge Reversals So Every Node Is Reachable - Problem

Imagine you have a network of cities connected by one-way roads. The network has a special property: if all roads were bidirectional, it would form a perfect tree structure with no cycles!

You're given n cities labeled from 0 to n-1 and a list of directed roads. Your mission is to find the minimum number of road reversals needed so that from each city, you can reach every other city by following the directed roads.

An edge reversal changes a road from "City A โ†’ City B" to "City B โ†’ City A".

Goal: For each starting city i, calculate independently how many roads need to be reversed to make all other cities reachable from city i.

Input: Number of cities n and array edges where edges[i] = [u, v] represents a road from city u to city v.

Output: Array where answer[i] is the minimum reversals needed when starting from city i.

Input & Output

example_1.py โ€” Basic Tree
$ Input: n = 4, edges = [[0,1],[1,2],[3,2]]
โ€บ Output: [1, 2, 0, 1]
๐Ÿ’ก Note: Tree: 0โ†’1โ†’2โ†3. For root 0: need to reverse 3โ†’2 (cost 1). For root 1: need to reverse 0โ†’1 and 3โ†’2 (cost 2). For root 2: no reversals needed (cost 0). For root 3: need to reverse 3โ†’2 (cost 1).
example_2.py โ€” Linear Chain
$ Input: n = 3, edges = [[0,1],[1,2]]
โ€บ Output: [0, 1, 2]
๐Ÿ’ก Note: Linear chain: 0โ†’1โ†’2. Root 0: no reversals (cost 0). Root 1: reverse 0โ†’1 (cost 1). Root 2: reverse both 0โ†’1 and 1โ†’2 (cost 2).
example_3.py โ€” Single Edge
$ Input: n = 2, edges = [[0,1]]
โ€บ Output: [0, 1]
๐Ÿ’ก Note: Simple edge 0โ†’1. Root 0: no reversals needed. Root 1: need to reverse 0โ†’1 to make it 1โ†’0.

Constraints

  • n == edges.length + 1
  • 1 โ‰ค n โ‰ค 105
  • edges[i].length == 2
  • 0 โ‰ค ui, vi โ‰ค n - 1
  • ui โ‰  vi
  • The input represents a tree (connected graph with n-1 edges)

Visualization

Tap to expand
Step 1: Initial Root01Cost from 0: 0Step 2: Reroot 0โ†’101Cost from 1: +1Step 3: Continue...Propagate cost changesto all other nodesusing tree structure๐ŸŽฏ Key Insight: O(n) solution by reusing computation!Instead of O(nยฒ) brute force, we calculate once and smartly adjust
Understanding the Visualization
1
Choose Initial Root
Pick node 0 as root, calculate total reversal cost via DFS
2
Reroot to Adjacent Node
When moving root from parent to child, adjust cost based on edge direction
3
Propagate Changes
Continue rerooting process through entire tree using calculated adjustments
Key Takeaway
๐ŸŽฏ Key Insight: Tree rerooting transforms an O(nยฒ) problem into O(n) by calculating once and intelligently propagating changes through the tree structure.
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 18
31.5K Views
Medium-High Frequency
~25 min Avg. Time
892 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