#3241
Time Taken to Mark All Nodes
HardDynamic ProgrammingTreeDepth-First SearchGraph TheoryDepth-First SearchGraph TraversalDynamic Programming on Trees
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can optimize the marking process using a depth-first search (DFS) approach to calculate the maximum time for marking all nodes based on their distances from the starting node. This allows us to avoid redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Build the adjacency list representation of the tree from the edges.
- 2Step 2: Use DFS to calculate the maximum marking time for each node based on its children.
- 3Step 3: For each node, determine the time taken to mark all nodes based on the maximum times of its children.
solution.py26 lines
1from collections import defaultdict
2
3def mark_nodes_optimal(edges):
4 n = len(edges) + 1
5 graph = defaultdict(list)
6 for u, v in edges:
7 graph[u].append(v)
8 graph[v].append(u)
9 times = [0] * n
10
11 def dfs(node, parent):
12 max_time_odd = 0
13 max_time_even = 0
14 for neighbor in graph[node]:
15 if neighbor == parent:
16 continue
17 dfs(neighbor, node)
18 if neighbor % 2 == 1:
19 max_time_odd = max(max_time_odd, times[neighbor] + 1)
20 else:
21 max_time_even = max(max_time_even, times[neighbor] + 2)
22 times[node] = max(max_time_odd, max_time_even)
23
24 for start in range(n):
25 dfs(start, -1)
26 return timesℹ
Complexity note: This complexity is due to the fact that we traverse each node and edge once, leading to O(n) time. The space complexity is O(n) for storing the graph.
- 1Marking time depends on the parity of nodes and their adjacency.
- 2Using DFS allows us to efficiently calculate marking times without redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.