Skip to content
Decoder

Reorder Routes to Make All Paths Lead to the City Zero

Medium

Problem

There are n cities numbered 0 to n - 1 and exactly n - 1 roads, so there is exactly one route between any two cities if you ignore direction. Every road is one-way: [a, b] lets you drive from a to b only. The capital is city 0. Return the minimum number of roads to reverse so that every city can drive to city 0.

Example 1

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

Example 2

Input
(flip 0
Output
1, 1→3 and 4→5)

Example 3

Input
n = 3, connections = [[1, 0], [2, 0]]
Output
0

Constraints

  • 2 <= n <= 5 * 10^4
  • connections.length == n - 1
  • 0 <= a, b < n and a != b

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.