1660. Reversals per Capital
A country has n cities numbered 0 to n-1 and n - 1 one-way roads; roads[i] = [a, b] means the road leads from city a to city b. Ignoring directions, the roads connect all cities with exactly one route between any two of them.
A city is picked as the capital, and the ministry wants every city to be able to drive to it. For each possible capital c, find the minimum number of roads whose direction must be flipped so that from every city a route to c exists. Return an array where entry c is that minimum. A flipped road replaces [a, b] by [b, a]; flips for different capitals are independent. With one city the answer is [0]. Computing each capital from scratch is O(n^2); reuse the answer of a neighbouring city to finish in O(n) time and O(n) space.
Example 1
- Input:
- n = 4, roads = [[0,1],[2,1],[3,1]]
- Output:
- [1,0,1,1]
- Explanation:
Capital 1 already receives all three roads, so it needs 0 flips; every other capital must flip exactly the one road that leaves it.
Example 2
- Input:
- n = 3, roads = [[1,0],[1,2]]
- Output:
- [1,2,1]
- Explanation:
Both roads leave city 1; capital 0 needs the road to city 2 flipped, capital 2 needs the road to city 0 flipped, and capital 1 needs both flipped.
Constraints
1 ≤ n ≤ 105; roads.length == n - 1; roads form a tree when directions are ignored
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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)