I started with brute force, picked an arbitrary root, ran a DFS to count reversals, then tried to re-run for every possible root.
Model the problem as rerooting on a tree: first root the tree arbitrarily and compute the number of reversals needed for that root using a post-order traversal. Then use a second DFS to compute the answer for all other roots by adjusting the count based on the direction of the edge between parent and child. Finally, return the minimum count over all nodes.
Pro tip: Clarify that the graph is a tree when ignoring directions, so there are no cycles; this allows O(n) rerooting. Also, mention that the minimum reversals equals the minimum number of edges pointing away from the root, which can be computed efficiently.
Confirm that the graph is a directed tree (underlying undirected graph is a tree) and that we need to find a root minimizing the number of edges that must be reversed to point away from it. Note that n can be large, so an O(n^2) solution is too slow.
Pick any node (e.g., 0) as the initial root. Perform a DFS/BFS to compute the number of edges that need reversal for this root: count edges directed toward the root (since they need to be reversed to point away).
Use a second DFS to propagate the reversal count from parent to child. When moving the root from u to v, if the edge u->v exists, the count decreases by 1 (since it already points away from v); if v->u exists, the count increases by 1.
Track the minimum reversal count across all nodes during the rerooting process. Return that minimum as the answer.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.