InterviewPrepKit

Home / Coding / Graphs

Reorder Routes to Make All Paths Lead to the City Zero

medium Original ↗
Solving tips
  • Root the tree at city 0 and do one DFS/BFS outward; every edge you cross that points AWAY from 0 (parent->child) must be reversed.
  • Store each road twice in the adjacency list: the real edge with flag 1 and a phantom reverse with flag 0, so you can walk the undirected tree while knowing true direction; add flag on crossing to neighbors.
  • O(n) time and space since it's a tree, one traversal, each node visited once.
  • Pitfall: keep a visited guard (the phantom reverse edges make it undirected, so you'd bounce to the parent), and with n up to 5e4 prefer BFS to avoid recursion-depth overflow on a path-shaped tree.

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.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.