Problem Description
Given an undirected tree with n nodes (numbered 0 to n - 1) and an edge list, we simulate a marking process. Initially, all nodes are unmarked. For a given starting node that is marked at time t = 0, every second the process marks all unmarked nodes with at least one marked neighbor. For each possible starting node, return the node that is marked last (if there are several candidates, any one is accepted).
Key Insights
- The marking process proceeds in “waves”, similar to a breadth-first search (BFS) level traversal.
- In a tree, the last marked node when starting from a source is simply one of the nodes at maximum distance from the source.
- A core observation is that, in a tree, for every vertex, the farthest node from it must be one of the endpoints of the tree's diameter.
- Thus, by computing the two farthest nodes (endpoints of the tree's diameter), we can determine for each starting node which endpoint is farther and therefore will be the last marked.
Space and Time Complexity
Time Complexity: O(n), since we perform a constant number of BFS traversals. Space Complexity: O(n), for storing the tree as an adjacency list and the distance arrays.
Solution
We first compute one endpoint of the diameter by running a BFS from an arbitrary node. Then, from that node, we perform a BFS to find the farthest node, which gives us the other endpoint of the diameter. Next, we run two BFS traversals starting from each endpoint (u and v) to compute the distances of every node from u and v respectively. Finally, for each starting node s, we choose the endpoint (u or v) which is farther from s; this endpoint is the last node to be marked during the marking process. This approach leverages the property that the furthest node from any source in a tree lies on its diameter, making the solution efficient even for large trees.