#2440

Create Components With Same Value

Hard
ArrayMathTreeDepth-First SearchEnumerationDFS for tree traversal.Graph representation using adjacency lists.
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach leverages the fact that we only need to consider the divisors of the total sum of the node values. By using a DFS to calculate component sums, we can efficiently determine how many edges can be deleted.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the total sum of the nums array.
  2. 2Step 2: Find all divisors of the total sum.
  3. 3Step 3: For each divisor, use DFS to check how many components can be formed with that sum.
  4. 4Step 4: Keep track of the maximum number of edges that can be deleted for valid components.
solution.py35 lines
1# Full working Python code
2from collections import defaultdict
3
4def maxEdgesToDelete(nums, edges):
5    total_sum = sum(nums)
6    n = len(nums)
7    graph = defaultdict(list)
8    for a, b in edges:
9        graph[a].append(b)
10        graph[b].append(a)
11    
12    def dfs(node, parent):
13        component_sum = nums[node]
14        for neighbor in graph[node]:
15            if neighbor != parent:
16                component_sum += dfs(neighbor, node)
17        return component_sum
18    
19    max_deletions = 0
20    for divisor in range(1, total_sum + 1):
21        if total_sum % divisor == 0:
22            current_sum = 0
23            deletions = 0
24            visited = [False] * n
25            for i in range(n):
26                if not visited[i]:
27                    component_sum = dfs(i, -1)
28                    if component_sum == divisor:
29                        deletions += 1
30                    current_sum += component_sum
31                    visited[i] = True
32            if current_sum == total_sum:
33                max_deletions = max(max_deletions, deletions - 1)
34    return max_deletions
35

Complexity note: The time complexity is O(n) as we only traverse the tree once for each divisor, and the space complexity is O(n) due to the graph representation.

  • 1Understanding the relationship between the total sum of node values and the components formed is crucial.
  • 2Divisors of the total sum guide the possible valid component sums.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.