Reorder Routes to Make All Paths Lead to the City Zero - Problem

There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network forms a tree).

Last year, the ministry of transport decided to orient the roads in one direction because they are too narrow.

Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.

This year, there will be a big event in the capital (city 0), and many people want to travel to this city.

Your task consists of reorienting some roads such that each city can visit city 0. Return the minimum number of edges changed.

It's guaranteed that each city can reach city 0 after reorder.

Input & Output

Example 1 — Basic Tree
$ Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
💡 Note: Start DFS from city 0. Need to reverse edges 1→3, 2→3, and 4→5 so all cities can reach city 0. Edges 0→1 and 4→0 are already pointing toward city 0.
Example 2 — Linear Chain
$ Input: n = 4, connections = [[1,0],[1,2],[3,2]]
Output: 2
💡 Note: Start from city 0. Edge 1→0 is correct (points to 0). Need to reverse 1→2 and 3→2 so cities 2 and 3 can reach city 0 through city 1.
Example 3 — Minimum Case
$ Input: n = 2, connections = [[1,0]]
Output: 0
💡 Note: Only one edge 1→0, which already points toward city 0. No reversals needed.

Constraints

  • 2 ≤ n ≤ 5 × 104
  • connections.length == n - 1
  • connections[i].length == 2
  • 0 ≤ ai, bi ≤ n - 1
  • ai ≠ bi

Visualization

Tap to expand
Reorder Routes: Make All Paths Lead to City ZeroOriginal Graph0120→11→0 (wrong)2→0 (wrong)After DFS Analysis0120→1 (keep)1→0 (reversed)2→0 (reversed)ResultEdges to Reverse:2(1→0 and 2→0)Algorithm Steps1. Build undirected graph2. Track edge directions3. DFS from city 04. Count wrong directionsKey InsightBuild undirected graph butremember original directions.Count edges pointing awayfrom city 0 during traversal.ComplexityTime: O(n)Space: O(n)Single traversalvisits each edge once🎯 Core idea: Traverse tree from city 0 and count edges going the wrong way
Understanding the Visualization
1
Input Graph
Directed edges between cities, need all paths to lead to city 0
2
DFS Traversal
Start from city 0, track which edges point away and need reversal
3
Count Reversals
Total number of edges that must be reversed
Key Takeaway
🎯 Key Insight: Build undirected graph but track original directions - count edges pointing away from city 0
Asked in
Amazon 35 Microsoft 28 Google 22
89.2K Views
Medium Frequency
~25 min Avg. Time
1.8K 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