#2322
Minimum Score After Removals on a Tree
HardArrayBit ManipulationTreeDepth-First SearchTree 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)
The optimal approach leverages the properties of XOR and tree structure. By calculating the XOR for each subtree in advance, we can efficiently determine the scores for different edge removals without redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the total XOR of all node values.
- 2Step 2: For each edge, calculate the XOR of the subtree formed by removing that edge.
- 3Step 3: Store the XOR values of all subtrees. For each pair of edges, compute the score using the precomputed values.
solution.py36 lines
1# Full working Python code
2import collections
3
4class Solution:
5 def minScore(self, nums, edges):
6 graph = collections.defaultdict(list)
7 for a, b in edges:
8 graph[a].append(b)
9 graph[b].append(a)
10
11 total_xor = 0
12 for num in nums:
13 total_xor ^= num
14
15 subtree_xor = [0] * len(nums)
16 visited = [False] * len(nums)
17
18 def dfs(node):
19 visited[node] = True
20 xor_sum = nums[node]
21 for neighbor in graph[node]:
22 if not visited[neighbor]:
23 xor_sum ^= dfs(neighbor)
24 subtree_xor[node] = xor_sum
25 return xor_sum
26
27 dfs(0)
28
29 min_score = float('inf')
30 for a, b in edges:
31 xor1 = subtree_xor[a]
32 xor2 = total_xor ^ xor1
33 score = abs(xor1 - xor2)
34 min_score = min(min_score, score)
35
36 return min_scoreℹ
Complexity note: This complexity arises because we traverse the tree once to compute the total XOR and subtree XORs, making it efficient compared to the brute force method.
- 1Understanding the properties of XOR can significantly reduce the complexity of the problem.
- 2Precomputing values like subtree XORs allows for efficient calculations when considering edge removals.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.