Find the Last Marked Nodes in Tree - Problem

Imagine a viral spread simulation on a tree network! You have an undirected tree with n nodes numbered from 0 to n-1, connected by n-1 edges.

Here's how the simulation works:

  • At time t = 0, you mark exactly one node as the initial infection source
  • Every second after that, the infection spreads to all unmarked nodes that are adjacent to any already marked node
  • This continues until every node in the tree is marked

Your task: For each possible starting node i, determine which node will be the very last to get marked. Return an array where result[i] is the last node to be marked when starting from node i.

Note: If there are multiple nodes that could be last (tied for the same time), you can return any of them.

Input & Output

example_1.py โ€” Basic Tree
$ Input: edges = [[0,1],[0,2],[1,3]]
โ€บ Output: [3, 3, 3, 3]
๐Ÿ’ก Note: Tree: 2-0-1-3. Starting from any node, node 3 is always the farthest (or tied for farthest), so it gets marked last in all cases.
example_2.py โ€” Linear Tree
$ Input: edges = [[0,1],[1,2],[2,3],[3,4]]
โ€บ Output: [4, 4, 4, 0, 0]
๐Ÿ’ก Note: Linear tree: 0-1-2-3-4. When starting from nodes 0,1,2, node 4 is farthest. When starting from nodes 3,4, node 0 is farthest.
example_3.py โ€” Single Node
$ Input: edges = []
โ€บ Output: [0]
๐Ÿ’ก Note: Only one node exists (node 0), so when starting from node 0, node 0 itself is the last (and only) node to be marked.

Constraints

  • 1 โ‰ค n โ‰ค 105
  • edges.length == n - 1
  • 0 โ‰ค ui, vi < n
  • The input represents a valid tree (connected and acyclic)

Visualization

Tap to expand
0t=0 (Start)1t=12t=13t=2 (Last)Marking Wavesโ— t=0: Initial node markedโ— t=1: Adjacent nodes markedโ— t=2: Next level nodes markedPattern continues until all nodesare marked. The last node isalways at maximum distance!
Understanding the Visualization
1
Initialize
Mark the starting node at time t=0
2
Wave 1
At t=1, mark all direct neighbors of initially marked nodes
3
Wave 2+
Continue marking neighbors of newly marked nodes each second
4
Final Wave
The last wave contains the final node(s) to be marked
Key Takeaway
๐ŸŽฏ Key Insight: The marking process spreads in waves like a breadth-first search. The last node to be marked is always at the maximum distance from the starting point, which corresponds to one of the tree's diameter endpoints!
Asked in
Google 28 Amazon 22 Meta 15 Microsoft 12
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen