690. Point Roads to Capital

A small country has n cities numbered 0 to n - 1 and exactly n - 1 one-way roads. Each entry [a, b] of connections is a road that can only be driven from city a to city b. If the directions were ignored, the roads would link all cities into a single network without any cycle.

The government wants every city to be able to drive to the capital, city 0. To achieve this it may reverse the direction of some roads. Return the smallest number of roads that must be reversed. Your solution should run in O(n) time and must not rely on deep recursion, since the road network can be one very long chain.

Example 1

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

The cities form the line 0-1-2-3-4. Roads 0 to 1 and 1 to 2 point away from the capital and 3 to 4 does too, while 3 to 2 already points towards it, so 3 roads are reversed.

Example 2

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

Every road already leads into city 0 directly, so nothing needs to change.

Example 3

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

Roads 1 to 2 and 4 to 5 lead away from city 0, the other three lead towards it, so exactly 2 roads are reversed.

Constraints

1 ≤ n ≤ 100000

connections.length == n - 1

0 ≤ a, b < n and a ≠ b for every road [a, b]

Ignoring directions, the roads form a tree (connected, no cycle).

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…