I went straight for recursive DFS and got maybe halfway through before the interviewer asked what happens with large n.
Model the problem as a tree rooted at node 0, where each edge has a cost: 0 if it points away from the root, 1 if it points toward the root. Then compute the sum of costs along the path from the root to each node using a single DFS/BFS, which gives the minimum reversals for each node. This works because reversing an edge only affects the direction of that edge, and the path from root to node is unique in a tree.
Pro tip: Clarify that the graph is a tree (undirected edges with directions) and that the minimum reversals for a node is simply the number of edges on the unique path from root that are directed toward the root. This avoids overcomplicating with dynamic programming or multiple passes.
Confirm that the graph is a tree (n nodes, n-1 edges) and that we need the minimum reversals for each node to be reachable from node 0. Note that reversing an edge changes its direction, and we want the minimum number of such changes.
Assign a cost of 0 to an edge if it is directed away from the root (i.e., from parent to child in the rooted tree) and a cost of 1 if it is directed toward the root (child to parent). This cost represents the need to reverse that edge.
Perform a DFS or BFS starting from node 0, keeping track of the cumulative cost from the root to the current node. For each child, add the cost of the edge connecting them.
For each node, the cumulative cost from the root is the minimum number of reversals needed. Store these values in an array of length n.
The algorithm runs in O(n) time and O(n) space. Consider edge cases: n=1 (result [0]), and ensure the tree is connected.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.