Leetcode #2440: Create Components With Same Value
In this guide, we solve Leetcode #2440 Create Components With Same Value in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
There is an undirected tree with n nodes labeled from 0 to n - 1. You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the ith node.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Tree, Depth-First Search, Array, Math, Enumeration
Intuition
We need to explore a structure deeply before backing up, which suits DFS.
DFS keeps local context on the call stack and is easy to implement recursively.
Approach
Define a recursive DFS that carries the necessary state.
Combine child results as the recursion unwinds.
Steps:
- Define a recursive DFS with state.
- Visit children and combine results.
- Return the final aggregation.
Example
Input: nums = [6,2,2,2,6], edges = [[0,1],[1,2],[1,3],[3,4]]
Output: 2
Explanation: The above figure shows how we can delete the edges [0,1] and [3,4]. The created components are nodes [0], [1,2,3] and [4]. The sum of the values in each component equals 6. It can be proven that no better deletion exists, so the answer is 2.
Python Solution
class Solution:
def componentValue(self, nums: List[int], edges: List[List[int]]) -> int:
def dfs(i, fa):
x = nums[i]
for j in g[i]:
if j != fa:
y = dfs(j, i)
if y == -1:
return -1
x += y
if x > t:
return -1
return x if x < t else 0
n = len(nums)
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
s = sum(nums)
mx = max(nums)
for k in range(min(n, s // mx), 1, -1):
if s % k == 0:
t = s // k
if dfs(0, -1) == 0:
return k - 1
return 0
Complexity
The time complexity is , where and are the length of and the sum of the values of all nodes in , respectively. The space complexity is O(V).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.