Skip to content
Problem 1466 · LeetCode 1466(opens in a new tab)

Reorder Routes to Make All Paths Lead to the City Zero

MediumGraphs

There are n cities, numbered 0 to n − 1, and n − 1 one-way roads. Ignoring direction, the roads connect every city with exactly one route between any two. Each road connections[i] = [a, b] lets you drive from a to b only.

Everyone wants to drive to city 0. Return the fewest roads whose direction you must turn around so that every city can reach city 0.

Example 1

Input:  n = 5, connections = [[3, 4], [2, 1], [0, 1], [3, 0]]
Output: 2
Why:    turn 0 -> 1 and 3 -> 4 around
2 more examples and the constraints

Example 2

Input:  n = 4, connections = [[1, 0], [2, 1], [3, 2]]
Output: 0
Why:    3 -> 2 -> 1 -> 0 already works

Example 3

Input:  n = 3, connections = [[0, 1], [0, 2]]
Output: 2
Why:    both roads lead out of 0

Constraints

  • 2 ≤ n ≤ 50,000
  • connections has n − 1 roads, each [a, b] with a ≠ b and 0 ≤ a, b < n
  • Ignoring direction, the roads form a tree

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Repeat passes over the roadsO(n²)
  2. BFS from city 0O(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 50,000 citiesVerdict
Repeat passes over the roadsO(n²)
Fine on small input; too slow worst case
BFS from city 0O(n)
Best; each road read twice

n = number of cities; there are n − 1 roads.

Edge cases to test

  • Already done. A chain 3 → 2 → 1 → 0 needs 0 changes.
  • Every road wrong. A chain 0 → 1 → 2 → 3 → 4 needs all 4 roads turned.
  • Two cities. The answer is 1 for [[0, 1]] and 0 for [[1, 0]].
  • City 0 is a leaf. Nothing special: the walk just has one road to start from.

Common mistakes

  • Building the graph with only the road's own direction, so the walk from 0 cannot go against a road and misses cities.
  • Counting roads that point toward 0 instead of away from it.
  • Using recursive DFS in Python on a 50,000-city chain and hitting the recursion limit.

How to talk through it

  1. 1Clarify. Do the roads always form a tree, so there is one route between any two cities? (Yes.)
  2. 2Give the slow sweep. Grow the set that reaches 0 by scanning the roads again and again: O(n²) in the worst order.
  3. 3Walk out from 0. Moving away from 0, a road you can follow is pointing the wrong way.
  4. 4Code the BFS. Store both directions with a 1 or 0 flag and add the flags of the roads walked.
  5. 5Test out loud. Run a chain that already works, a chain that is all wrong, and two cities.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?