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, 2, 3, 2]
💡 Note: Tree: 2-0-1-3. Starting from 0: node 3 is farthest. Starting from 1: node 2 is farthest (distance 3). Starting from 2: node 3 is farthest (distance 3). Starting from 3: node 2 is farthest (distance 3).
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
Find the Last Marked Nodes in Tree INPUT Tree Structure (n=4 nodes) 0 1 2 3 edges = [[0,1],[0,2],[1,3]] Edge 0-1: connects nodes 0,1 Edge 0-2: connects nodes 0,2 Edge 1-3: connects nodes 1,3 ALGORITHM (DP) 1 Find Tree Diameter Use BFS/DFS to find endpoints 2 Compute Distances DP: dist from each node to all 3 Find Farthest Node For each start, find max dist 4 Build Result Array Store last marked node per start Distance Table (BFS from each) From 0 1 2 3 Last 0 0 1 1 2 3 1 1 0 2 1 3 2 1 2 0 3 3 3 3 1 3 0 3 FINAL RESULT Node 3 is always last! 0 1 2 3 LAST Output Array 3 3 3 3 [0] [1] [2] [3] OK - All return node 3 Key Insight: The last node to be marked is always the FARTHEST node from the starting point. Node 3 is at the end of the tree's diameter (longest path), so it's the farthest from every other node. DP approach: Precompute all pairwise distances in O(n) using tree rerooting technique. TutorialsPoint - Find the Last Marked Nodes in Tree | DP Approach
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