progress

~/problems / Trees / Tree DP

Best root for a one-way tree

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~25 min Uber

A city has n intersections, numbered 1..n, joined by n - 1 one-way streets. Ignoring the directions, the streets form a tree. Street i runs from frm[i] to to[i].

The city wants to pick one intersection as a dispatch hub and then flip the direction of as few streets as possible so that every street points away from the hub (so every intersection can be reached from the hub by driving forwards).

Write min_reversals(n: int, frm: list[int], to: list[int]) -> int that returns the fewest flips needed, taking the best possible hub.

min_reversals(4, [2, 2, 4], [1, 3, 3])
# 1: streets 2->1, 2->3, 4->3. Hub 2 needs only 4->3 flipped (hub 4 also needs just one flip).
One-way streets 2 to 1, 2 to 3 and 4 to 3; with 2 as the hub, only the street 4 to 3 has to be flipped so every street points away from it
min_reversals(3, [1, 2], [2, 3])   # 0   (hub 1: 1->2->3 already points away)
min_reversals(1, [], [])           # 0

Constraints: 1 <= n <= 10**5.

⭐ Bonus: speed tests on 100,000-node trees (one is a single path, too deep for recursion) earn a star in O(n). Trying every hub and walking the whole tree from each is O(n²).

Show hint

Compute the answer for hub 1 with one traversal. Then ask how that number changes when the hub moves across a single street to a neighbour.

Topic: Tree DP. Post-order: each node returns a small tuple of states to its parent.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc