Minimum Score After Removals on a Tree - Problem

Imagine you have a connected tree with n nodes (labeled 0 to n-1) where each node has a specific value. Your task is to strategically remove exactly two edges to split this tree into three separate components.

Here's the challenge: For each possible pair of edge removals, you need to:

  • Calculate the XOR of all node values in each of the three resulting components
  • Find the difference between the largest and smallest XOR values (this is your "score")
  • Minimize this score across all possible edge removal pairs

Example: If removing two edges creates components with node values [4,5,7], [1,9], and [3,3,3], the XOR values would be 4^5^7=6, 1^9=8, and 3^3^3=3. The score would be max(6,8,3) - min(6,8,3) = 8-3 = 5.

Return the minimum possible score among all valid edge removal combinations.

Input & Output

example_1.py — Basic Tree
$ Input: nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]]
› Output: 9
šŸ’” Note: Removing edges [1,3] and [3,4] creates components with XOR values [1āŠ•5=4, 5, 4āŠ•11=15]. Score = 15-4 = 11. The optimal removal gives score 9.
example_2.py — Small Tree
$ Input: nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]]
› Output: 0
šŸ’” Note: There exists a way to remove two edges such that all three components have the same XOR value, resulting in a score of 0.
example_3.py — Minimal Tree
$ Input: nums = [1,2,3], edges = [[0,1],[1,2]]
› Output: 2
šŸ’” Note: Only one way to split: remove both edges to get components [1], [2], [3] with XORs 1, 2, 3. Score = 3-1 = 2.

Constraints

  • 3 ≤ n ≤ 1000
  • edges.length == n - 1
  • 0 ≤ nums[i] ≤ 28
  • The given edges form a valid tree
  • Each edge connects two distinct nodes
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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