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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code