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.
Example 1:
Input:edges = [[0,1],[0,2]]
Output: [2,4,3]
Explanation:
For i = 0:
Node 1 is marked at t = 1, and Node 2 at t = 2.
For i = 1:
Node 0 is marked at t = 2, and Node 2 at t = 4.
For i = 2:
Node 0 is marked at t = 2, and Node 1 at t = 3.
Example 2:
Input:edges = [[0,1]]
Output: [1,2]
Explanation:
For i = 0:
Node 1 is marked at t = 1.
For i = 1:
Node 0 is marked at t = 2.
Example 3:
Input:edges = [[2,4],[0,1],[2,3],[0,2]]
Output: [4,6,3,5,5]
Explanation:
Constraints:
2 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= edges[i][0], edges[i][1] <= n - 1
The input is generated such that edges represents a valid tree.
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming · Tree
Example 1
[[0,1],[0,2]]
Example 2
[[0,1]]
Example 3
[[2,4],[0,1],[2,3],[0,2]]
Related Problems
Sum of Distances in Tree (sum-of-distances-in-tree)
Most Profitable Path in a Tree (most-profitable-path-in-a-tree)
Find the Last Marked Nodes in Tree (find-the-last-marked-nodes-in-tree)
Step 02
Core Insight
What unlocks the optimal approach
Can we use dp on trees?
Store the two most distant children for each node.
When re-rooting the tree, keep a variable for distance to the root node.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3241: Time Taken to Mark All Nodes
class Solution {
public int[] timeTaken(int[][] edges) {
final int n = edges.length + 1;
int[] ans = new int[n];
List<Integer>[] tree = new List[n];
// dp[i] := the top two direct child nodes for subtree rooted at node i,
// where each node contains the time taken to mark the entire subtree rooted
// at the node itself
Top2[] dp = new Top2[n];
for (int i = 0; i < n; ++i) {
tree[i] = new ArrayList<>();
dp[i] = new Top2();
}
for (int[] edge : edges) {
final int u = edge[0];
final int v = edge[1];
tree[u].add(v);
tree[v].add(u);
}
dfs(tree, 0, /*prev=*/-1, dp);
reroot(tree, 0, /*prev=*/-1, /*maxTime=*/0, dp, ans);
return ans;
}
private record Node(int node, int time) {
Node() {
this(0, 0);
}
}
private record Top2(Node max1, Node max2) {
Top2() {
this(new Node(), new Node());
}
}
// Return the time taken to mark node u.
private int getTime(int u) {
return u % 2 == 0 ? 2 : 1;
}
// Performs a DFS traversal of the subtree rooted at node `u`, computes the
// time taken to mark all nodes in the subtree, records the top two direct
// child nodes, where the time taken to mark the subtree rooted at each of the
// child nodes is maximized, and returns the top child node.
//
// These values are used later in the rerooting process.
private int dfs(List<Integer>[] tree, int u, int prev, Top2[] dp) {
Node max1 = new Node();
Node max2 = new Node();
for (final int v : tree[u]) {
if (v == prev)
continue;
final int time = dfs(tree, v, u, dp) + getTime(v);
if (time >= max1.time()) {
max2 = max1;
max1 = new Node(v, time);
} else if (time > max2.time()) {
max2 = new Node(v, time);
}
}
dp[u] = new Top2(max1, max2);
return max1.time();
}
// Reroots the tree at node `u` and updates the answer array, where `maxTime`
// is the longest path that doesn't go through `u`'s subtree.
private void reroot(List<Integer>[] tree, int u, int prev, int maxTime, Top2[] dp, int[] ans) {
ans[u] = Math.max(maxTime, dp[u].max1().time());
for (final int v : tree[u]) {
if (v == prev)
continue;
final int newMaxTime =
getTime(u) +
Math.max(maxTime, dp[u].max1().node() == v ? dp[u].max2().time() : dp[u].max1().time());
reroot(tree, v, u, newMaxTime, dp, ans);
}
}
}
// Accepted solution for LeetCode #3241: Time Taken to Mark All Nodes
package main
// https://space.bilibili.com/206214
func timeTaken(edges [][]int) []int {
n := len(edges) + 1
g := make([][]int, n)
for _, e := range edges {
x, y := e[0], e[1]
g[x] = append(g[x], y)
g[y] = append(g[y], x)
}
// subRes[x] 保存子树 x 的最大深度 maxD,次大深度 maxD2,以及最大深度要往儿子 y 走
subRes := make([]struct{ maxD, maxD2, y int }, n)
// 计算 subRes[x]
var dfs func(int, int)
dfs = func(x, fa int) {
res := &subRes[x]
for _, y := range g[x] {
if y == fa {
continue
}
dfs(y, x)
w := 2 - y%2 // 从 x 到 y 的边权
maxD := subRes[y].maxD + w // 从 x 出发,往 y 方向的最大深度
if maxD > res.maxD {
res.maxD2 = res.maxD
res.maxD = maxD
res.y = y
} else if maxD > res.maxD2 {
res.maxD2 = maxD
}
}
}
dfs(0, -1)
// ans[x] 表示当 x 是树根时,整棵树的最大深度
ans := make([]int, n)
// 计算 ans[x]
var reroot func(int, int, int)
reroot = func(x, fa, fromUp int) {
sub := subRes[x]
ans[x] = max(sub.maxD, fromUp)
for _, y := range g[x] {
if y == fa {
continue
}
// 站在 x 的角度,不往 y 走,能走多远?
// 要么往上走(fromUp),要么往除了 y 的其余子树走(mx),二者取最大值
mx := sub.maxD
if y == sub.y { // 对于 y 来说,上面要选次大的
mx = sub.maxD2
}
w := 2 - x%2 // 从 y 到 x 的边权
reroot(y, x, max(fromUp, mx)+w) // 对于 y 来说,加上从 y 到 x 的边权
}
}
reroot(0, -1, 0)
return ans
}
# Accepted solution for LeetCode #3241: Time Taken to Mark All Nodes
from dataclasses import dataclass
@dataclass
class Node:
node: int = 0 # the node number
time: int = 0 # the time taken to mark the entire subtree rooted at the node
class Top2:
def __init__(self, top1: Node = Node(), top2: Node = Node()):
# the direct child node, where the time taken to mark the entire subtree
# rooted at the node is the maximum
self.top1 = top1
# the direct child node, where the time taken to mark the entire subtree
# rooted at the node is the second maximum
self.top2 = top2
class Solution:
def timeTaken(self, edges: list[list[int]]) -> list[int]:
n = len(edges) + 1
ans = [0] * n
tree = [[] for _ in range(n)]
# dp[i] := the top two direct child nodes for subtree rooted at node i,
# where each node contains the time taken to mark the entire subtree rooted
# at the node itself
dp = [Top2()] * n
for u, v in edges:
tree[u].append(v)
tree[v].append(u)
self._dfs(tree, 0, -1, dp)
self._reroot(tree, 0, -1, 0, dp, ans)
return ans
def _getTime(self, u: int) -> int:
"""Returns the time taken to mark node u."""
return 2 if u % 2 == 0 else 1
def _dfs(
self,
tree: list[list[int]],
u: int,
prev: int,
dp: list[Top2]
) -> int:
"""
Performs a DFS traversal of the subtree rooted at node `u`, computes the
time taken to mark all nodes in the subtree, records the top two direct
child nodes, where the time taken to mark the subtree rooted at each of the
child nodes is maximized, and returns the top child node.
These values are used later in the rerooting process.
"""
top1 = Node()
top2 = Node()
for v in tree[u]:
if v == prev:
continue
time = self._dfs(tree, v, u, dp) + self._getTime(v)
if time >= top1.time:
top2 = top1
top1 = Node(v, time)
elif time > top2.time:
top2 = Node(v, time)
dp[u] = Top2(top1, top2)
return top1.time
def _reroot(
self,
tree: list[list[int]],
u: int,
prev: int,
maxTime: int,
dp: list[Top2],
ans: list[int]
) -> None:
"""
Reroots the tree at node `u` and updates the answer array, where `maxTime`
is the longest path that doesn't go through `u`'s subtree.
"""
ans[u] = max(maxTime, dp[u].top1.time)
for v in tree[u]:
if v == prev:
continue
newMaxTime = self._getTime(u) + max(
maxTime,
dp[u].top2.time if dp[u].top1.node == v else dp[u].top1.time
)
self._reroot(tree, v, u, newMaxTime, dp, ans)
// Accepted solution for LeetCode #3241: Time Taken to Mark All Nodes
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3241: Time Taken to Mark All Nodes
// class Solution {
// public int[] timeTaken(int[][] edges) {
// final int n = edges.length + 1;
// int[] ans = new int[n];
// List<Integer>[] tree = new List[n];
// // dp[i] := the top two direct child nodes for subtree rooted at node i,
// // where each node contains the time taken to mark the entire subtree rooted
// // at the node itself
// Top2[] dp = new Top2[n];
//
// for (int i = 0; i < n; ++i) {
// tree[i] = new ArrayList<>();
// dp[i] = new Top2();
// }
//
// for (int[] edge : edges) {
// final int u = edge[0];
// final int v = edge[1];
// tree[u].add(v);
// tree[v].add(u);
// }
//
// dfs(tree, 0, /*prev=*/-1, dp);
// reroot(tree, 0, /*prev=*/-1, /*maxTime=*/0, dp, ans);
// return ans;
// }
//
// private record Node(int node, int time) {
// Node() {
// this(0, 0);
// }
// }
//
// private record Top2(Node max1, Node max2) {
// Top2() {
// this(new Node(), new Node());
// }
// }
//
// // Return the time taken to mark node u.
// private int getTime(int u) {
// return u % 2 == 0 ? 2 : 1;
// }
//
// // Performs a DFS traversal of the subtree rooted at node `u`, computes the
// // time taken to mark all nodes in the subtree, records the top two direct
// // child nodes, where the time taken to mark the subtree rooted at each of the
// // child nodes is maximized, and returns the top child node.
// //
// // These values are used later in the rerooting process.
// private int dfs(List<Integer>[] tree, int u, int prev, Top2[] dp) {
// Node max1 = new Node();
// Node max2 = new Node();
// for (final int v : tree[u]) {
// if (v == prev)
// continue;
// final int time = dfs(tree, v, u, dp) + getTime(v);
// if (time >= max1.time()) {
// max2 = max1;
// max1 = new Node(v, time);
// } else if (time > max2.time()) {
// max2 = new Node(v, time);
// }
// }
// dp[u] = new Top2(max1, max2);
// return max1.time();
// }
//
// // Reroots the tree at node `u` and updates the answer array, where `maxTime`
// // is the longest path that doesn't go through `u`'s subtree.
// private void reroot(List<Integer>[] tree, int u, int prev, int maxTime, Top2[] dp, int[] ans) {
// ans[u] = Math.max(maxTime, dp[u].max1().time());
// for (final int v : tree[u]) {
// if (v == prev)
// continue;
// final int newMaxTime =
// getTime(u) +
// Math.max(maxTime, dp[u].max1().node() == v ? dp[u].max2().time() : dp[u].max1().time());
// reroot(tree, v, u, newMaxTime, dp, ans);
// }
// }
// }
// Accepted solution for LeetCode #3241: Time Taken to Mark All Nodes
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3241: Time Taken to Mark All Nodes
// class Solution {
// public int[] timeTaken(int[][] edges) {
// final int n = edges.length + 1;
// int[] ans = new int[n];
// List<Integer>[] tree = new List[n];
// // dp[i] := the top two direct child nodes for subtree rooted at node i,
// // where each node contains the time taken to mark the entire subtree rooted
// // at the node itself
// Top2[] dp = new Top2[n];
//
// for (int i = 0; i < n; ++i) {
// tree[i] = new ArrayList<>();
// dp[i] = new Top2();
// }
//
// for (int[] edge : edges) {
// final int u = edge[0];
// final int v = edge[1];
// tree[u].add(v);
// tree[v].add(u);
// }
//
// dfs(tree, 0, /*prev=*/-1, dp);
// reroot(tree, 0, /*prev=*/-1, /*maxTime=*/0, dp, ans);
// return ans;
// }
//
// private record Node(int node, int time) {
// Node() {
// this(0, 0);
// }
// }
//
// private record Top2(Node max1, Node max2) {
// Top2() {
// this(new Node(), new Node());
// }
// }
//
// // Return the time taken to mark node u.
// private int getTime(int u) {
// return u % 2 == 0 ? 2 : 1;
// }
//
// // Performs a DFS traversal of the subtree rooted at node `u`, computes the
// // time taken to mark all nodes in the subtree, records the top two direct
// // child nodes, where the time taken to mark the subtree rooted at each of the
// // child nodes is maximized, and returns the top child node.
// //
// // These values are used later in the rerooting process.
// private int dfs(List<Integer>[] tree, int u, int prev, Top2[] dp) {
// Node max1 = new Node();
// Node max2 = new Node();
// for (final int v : tree[u]) {
// if (v == prev)
// continue;
// final int time = dfs(tree, v, u, dp) + getTime(v);
// if (time >= max1.time()) {
// max2 = max1;
// max1 = new Node(v, time);
// } else if (time > max2.time()) {
// max2 = new Node(v, time);
// }
// }
// dp[u] = new Top2(max1, max2);
// return max1.time();
// }
//
// // Reroots the tree at node `u` and updates the answer array, where `maxTime`
// // is the longest path that doesn't go through `u`'s subtree.
// private void reroot(List<Integer>[] tree, int u, int prev, int maxTime, Top2[] dp, int[] ans) {
// ans[u] = Math.max(maxTime, dp[u].max1().time());
// for (final int v : tree[u]) {
// if (v == prev)
// continue;
// final int newMaxTime =
// getTime(u) +
// Math.max(maxTime, dp[u].max1().node() == v ? dp[u].max2().time() : dp[u].max1().time());
// reroot(tree, v, u, newMaxTime, dp, ans);
// }
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.