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 i is odd, the node will get marked at time x if there is at least one node adjacent to it which was marked at time x - 1.
  • If i is even, the node will get marked at time x if there is at least one node adjacent to it which was marked at time x - 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
Time Taken to Mark All Nodes: Asymmetric Tree SpreadingInput: edges = [[0,1],[1,2]] → Linear tree: 0---1---20even1odd2evenStart from 0:0→1: +1 (odd) = t11→2: +2 (even) = t3Max time: 3Start from 1:1→0: +2 (even) = t21→2: +2 (even) = t2Max time: 2Start from 2:2→1: +1 (odd) = t11→0: +2 (even) = t3Max time: 3Output: [3, 2, 3]🎯 Key Insight: Node parity affects marking speed, creating asymmetric spread patterns
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
Asked in
Meta 8 Google 5
8.4K Views
Medium Frequency
~35 min Avg. Time
256 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