Time Taken to Mark All Nodes - Problem
There exists an undirected tree with n nodes numbered 0 to n - 1. You are given a 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the tree.
Initially, all nodes are unmarked. For each node i:
- If
iis odd, the node will get marked at timexif there is at least one node adjacent to it which was marked at timex - 1. - If
iis even, the node will get marked at timexif there is at least one node adjacent to it which was marked at timex - 2.
Return an array times where times[i] is the time when all nodes get marked in the tree, if you mark node i at time t = 0.
Note that the answer for each times[i] is independent, i.e. when you mark node i all other nodes are unmarked.
Input & Output
Example 1 — Simple Chain
$
Input:
edges = [[0,1],[1,2]]
›
Output:
[4,2,3]
💡 Note:
Starting from node 0: 0→1 (t=1) then 1→2 (t=3), max=3. Starting from node 1: 1→0 (t=2) and 1→2 (t=3), max=3. Starting from node 2: 2→1 (t=1) then 1→0 (t=3), max=3.
Example 2 — Single Edge
$
Input:
edges = [[0,1]]
›
Output:
[1,2]
💡 Note:
From node 0: mark node 1 at time 1 (odd). From node 1: mark node 0 at time 2 (even).
Example 3 — Star Graph
$
Input:
edges = [[1,0],[1,2],[1,3]]
›
Output:
[2,2,2,2]
💡 Note:
Node 1 connects to all others. From any node, the maximum time depends on the parity rules and distances.
Constraints
- 1 ≤ n ≤ 105
- edges.length == n - 1
- 0 ≤ ui, vi ≤ n - 1
- The given input represents a valid tree.
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Undirected tree with nodes 0,1,2 connected linearly
2
Marking Rules
Odd nodes: +1 time, Even nodes: +2 time from marked neighbor
3
All Starting Points
Calculate max marking time for each possible starting node
Key Takeaway
🎯 Key Insight: Different marking speeds based on node parity create complex timing dependencies in tree traversal
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code