Reorder Routes to Make All Paths Lead to The City Zero

Medium Topics Company Tags

There are n cities labeled 0 through n - 1. The pairs in connections describe one-way roads: [a, b] lets you travel from city a to city b. Ignoring their directions, the roads form a tree.

You may reverse the direction of any road. Return the minimum number of reversals needed so that every city has a directed path to city 0.

Reversing a road changes only its direction; its endpoints remain the same.

Example 1:

Reorder Routes to Make All Paths Lead to the City Zero, example 1: illustration of the example

Input: n = 4
connections = [[0,1],[2,1],[2,3]]

Output: 2

Explanation: Reverse 0 → 1 and 2 → 3. The resulting roads are 1 → 0, 2 → 1, and 3 → 2, so every city can reach 0. Both reversals are necessary.

Example 2:

Reorder Routes to Make All Paths Lead to the City Zero, example 2: illustration of the example

Input: n = 4
connections = [[1,0],[2,0],[3,0]]

Output: 0

Explanation: Each of cities 1, 2, and 3 already has a road directly to city 0. No road needs to change direction.

Example 3:

Reorder Routes to Make All Paths Lead to the City Zero, example 3: illustration of the example

Input: n = 5
connections = [[0,1],[0,2],[0,3],[0,4]]

Output: 4

Explanation: All four roads point away from city 0. Each leaf has only one road, so all four roads must be reversed.

Constraints:

  • 2 <= n <= 50000
  • connections.length == n - 1
  • connections[i].length == 2
  • Each road joins two distinct city labels between 0 and n - 1.
  • Ignoring road directions, the connections form a tree.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.