InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Reorder Routes to Make All Paths Lead to the City Zero

medium Original ↗ 00:00

Problem

There are n cities labeled 0 to n - 1. There are n - 1 directed roads in connections, where connections[i] = [a, b] is a road from city a to city b. If you ignore the directions, the roads form a tree — every city is connected, with no cycles.

Some roads point the “wrong way.” Return the minimum number of roads whose direction must be reversed so that every city can reach city 0 by following the roads.

Examples

  • connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]3 — reverse 0→1, 1→3, 4→5 so all cities can reach 0.
  • connections = [[1,0],[1,2],[3,2]]2 — reverse 1→2 and 3→2 (equivalently the roads pointing away from 0).
  • connections = [[1,0],[2,0]]0 — both roads already point toward city 0, so nothing needs reversing.

Constraints

  • 2 <= n <= 5 * 10^4
  • connections.length == n - 1; undirected, the roads form a tree.
  • Roads are directed; connections[i] = [a, b] means a → b.

Think about it first

Hint 1 Ignore direction and the graph is a tree rooted (conceptually) at city 0. Starting from 0 and walking outward, ask of each road: does it help you go *away* from 0 or *back toward* 0?
Hint 2 Build the graph storing, for each road, whether it's an "original" (points from parent to child, i.e. away from 0) or a "reverse" (already points toward 0). Traverse outward from 0. Every original edge you cross points the wrong way and must be reversed.
Hint 3 Use a DFS or BFS from node 0 over the undirected tree. For each neighbor you move to, if the real road goes parent→child, add 1 to the reversal count. The tree structure means you visit each city exactly once — no cycles to worry about.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug