Time Taken to Mark All Nodes
HardPrompt
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.
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 att = 2.
- Node 1 is marked at
- For
i = 1:- Node 0 is marked at
t = 2, and Node 2 att = 4.
- Node 0 is marked at
- For
i = 2:- Node 0 is marked at
t = 2, and Node 1 att = 3.
- Node 0 is marked at
Example 2:
Input: edges = [[0,1]]
Output: [1,2]
Explanation:

- For
i = 0:- Node 1 is marked at
t = 1.
- Node 1 is marked at
- For
i = 1:- Node 0 is marked at
t = 2.
- Node 0 is marked at
Example 3:
Input: edges = [[2,4],[0,1],[2,3],[0,2]]
Output: [4,6,3,5,5]
Explanation:

Constraints:
2 <= n <= 105edges.length == n - 1edges[i].length == 20 <= edges[i][0], edges[i][1] <= n - 1- The input is generated such that
edgesrepresents a valid tree.
Approaches
2 approaches with complexity analysis and trade-offs.
The most straightforward way to solve this problem is to simulate the marking process for each possible starting node. For each node i from 0 to n-1, we treat it as the initial node marked at time t=0 and calculate the time it takes for every other node in the tree to get marked. The final answer for i is the maximum of these times.
Algorithm
- For each node
ifrom0ton-1:- Initialize
distarray of sizenwith infinity,dist[i] = 0. - Create a deque and add
ito it. - While deque is not empty:
- Pop node
ufrom the front. - For each neighbor
vofu:- Calculate
cost = (v % 2 == 0) ? 2 : 1. - If
dist[u] + cost < dist[v]:- Update
dist[v] = dist[u] + cost. - If
cost == 1, addvto the front of the deque. - Else, add
vto the back.
- Update
- Calculate
- Pop node
- Find the maximum value in the
distarray and store it as the result for starting nodei.
- Initialize
Walkthrough
The problem of finding the time each node gets marked, given a starting node, can be modeled as a shortest path problem on a graph. The nodes of the graph are the nodes of the tree. The time it takes for a mark to propagate from a node u to an adjacent node v can be seen as the weight of a directed edge from u to v. This weight depends on the destination node v:
- If
vis odd, the time delay is 1. - If
vis even, the time delay is 2.
Since the edge weights are small positive integers (1 and 2), we can find the shortest path from a starting node s to all other nodes efficiently using a variation of Breadth-First Search (BFS), often called 0-1 BFS, which uses a deque instead of a standard queue.
The overall algorithm is as follows:
- Build an adjacency list representation of the tree from the
edgesinput. - Initialize an answer array
timesof sizen. - Loop through each node
ifrom0ton-1: a. Perform a 0-1 BFS starting from nodeito calculate the shortest time (dist[j]) for every other nodejto be marked. b. Thedistarray is initialized with infinity, anddist[i]is set to 0. c. A deque is used to store nodes to visit. Initially, it containsi. d. While the deque is not empty, extract a nodeu. For each neighborv, calculate the new timedist[u] + cost(v). If this is a shorter path tov, updatedist[v]and addvto the deque: to the front if the cost was 1, and to the back if the cost was 2. e. After the BFS completes, find the maximum value in thedistarray. This is the time when all nodes are marked. f. Store this maximum time intimes[i]. - Return the
timesarray.
This approach is correct but inefficient because it repeatedly calculates shortest paths over the same tree structure.
import java.util.*; class Solution { public int[] timeTaken(int[][] edges) { int n = edges.length + 1; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); } for (int[] edge : edges) { adj.get(edge[0]).add(edge[1]); adj.get(edge[1]).add(edge[0]); } int[] result = new int[n]; for (int i = 0; i < n; i++) { result[i] = calculateMaxTime(i, n, adj); } return result; } private int calculateMaxTime(int startNode, int n, List<List<Integer>> adj) { int[] dist = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); dist[startNode] = 0; Deque<Integer> deque = new ArrayDeque<>(); deque.addFirst(startNode); int maxTime = 0; while (!deque.isEmpty()) { int u = deque.pollFirst(); maxTime = Math.max(maxTime, dist[u]); for (int v : adj.get(u)) { int cost = (v % 2 == 0) ? 2 : 1; if (dist[u] != Integer.MAX_VALUE && dist[u] + cost < dist[v]) { dist[v] = dist[u] + cost; if (cost == 1) { deque.addFirst(v); } else { deque.addLast(v); } } } } return maxTime; }}Complexity
Time
O(N^2). For each of the `N` starting nodes, we perform a 0-1 BFS which takes `O(N + E)` time, where `E` is the number of edges. Since it's a tree, `E = N-1`, so one BFS is `O(N)`. The total time is `N * O(N) = O(N^2)`.
Space
O(N). We need `O(N)` space for the adjacency list, `O(N)` for the `dist` array, and `O(N)` for the deque in the worst case.
Trade-offs
Pros
Relatively simple to understand as it directly models the problem.
Correctly solves the problem for smaller inputs.
Cons
The
O(N^2)complexity is too slow for the given constraints (Nup to 10^5), leading to a "Time Limit Exceeded" error.
Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.