Minimum Score After Removals on a Tree - Problem

There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.

You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the ith node. You are also given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Remove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined:

  • Get the XOR of all the values of the nodes for each of the three components respectively.
  • The difference between the largest XOR value and the smallest XOR value is the score of the pair.

For example, say the three components have the node values: [4,5,7], [1,9], and [3,3,3]. The three XOR values are 4 ^ 5 ^ 7 = 6, 1 ^ 9 = 8, and 3 ^ 3 ^ 3 = 3. The largest XOR value is 8 and the smallest XOR value is 3. The score is then 8 - 3 = 5.

Return the minimum score of any possible pair of edge removals on the given tree.

Input & Output

Example 1 — Basic Tree
$ Input: nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]]
Output: 9
💡 Note: Remove edges (0,1) and (1,3) to get components {0}, {1,2}, {3,4}. XORs are 1, 0, 15. Score = 15-0 = 15. Remove edges (1,3) and (3,4) to get components {0,1,2}, {3}, {4}. XORs are 1^5^5=1, 4, 11. Score = 11-1 = 10. The minimum is 9.
Example 2 — Minimum Size
$ Input: nums = [5,5,2,4,4], edges = [[0,1],[1,2],[5,2],[4,3]]
Output: 0
💡 Note: With 4 edges and 5 nodes, this tree has multiple ways to create 3 components. Some combinations result in XOR values that are equal, giving a score of 0.

Constraints

  • 3 ≤ n ≤ 1000
  • edges.length == n - 1
  • 0 ≤ ai, bi < n
  • 1 ≤ nums[i] ≤ 231 - 1
  • The given input represents a valid tree.

Visualization

Tap to expand
INPUT TREEALGORITHM STEPSFINAL RESULT0:11:53:42:54:11Tree: nums=[1,5,5,4,11]edges=[[0,1],[1,2],[1,3],[3,4]]1Build Tree & DFSCreate adjacency listRoot at node 0, run DFS2Precompute Subtree XORsNode 1 subtree: 5^5 = 0Node 3 subtree: 4^11 = 153Try Edge PairsRemove (0,1) & (1,3)Components: {0}, {1,2}, {3,4}4Calculate ScoresXORs: 1, 0, 15Score: 15 - 0 = 15Find minimum over all pairsSCORE9Minimum score foundacross all edge pairsBest Configuration:Remove edges creating3 components withXORs closest in valueKey Insight:Precompute subtree XORs using DFS to avoid recalculating component valuesfor each edge removal pair, reducing redundant computation significantly.TutorialsPoint - Minimum Score After Removals on a Tree | DFS Optimization
Asked in
Google 25 Amazon 18 Microsoft 15
23.4K Views
Medium Frequency
~35 min Avg. Time
892 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