Total Sum of Interaction Cost in Tree Groups II - Solution & Explanation
Problem Statement
You are given an integer n and an undirected tree rooted at node 0 with n nodes numbered from 0 to n - 1. The tree is represented by a 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates an undirected edge between nodes ui and vi.
You are also given an integer array group of length n, where group[i] denotes the group label assigned to node i.
- Two nodes
uandvbelong to the same group if and only ifgroup[u] == group[v]. - The interaction cost between two nodes is the shortest distance between them in the tree.
Return the sum of interaction costs over all pairs of node indices (u, v) such that 0 <= u < v < n and group[u] == group[v].
The shortest distance between two nodes is the number of edges on the unique path connecting them in the tree.
Example 1:
Input: n = 3, edges = [[0,1],[1,2]], group = [1,1,1]
Output: 4
Explanation:

All nodes belong to group 1. The interaction costs between the pairs of nodes are:
- Nodes
[0, 1]: 1 - Nodes
[1, 2]: 1 - Nodes
[0, 2]: 2
Thus, the total interaction cost is 1 + 1 + 2 = 4.
Example 2:
Input: n = 3, edges = [[0,1],[1,2]], group = [3,2,3]
Output: 2
Explanation:

- Nodes 0 and 2 belong to group 3. The interaction cost between this pair is 2.
- Node 1 belongs to a different group and forms no valid pair. Therefore, the total interaction cost is 2.
Example 3:
Input: n = 4, edges = [[0,1],[0,2],[0,3]], group = [1,1,4,4]
Output: 3
Explanation:
āāāāāāāāāāāāāā
Nodes belonging to the same groups and their interaction costs are:
- Group 1: Nodes
[0, 1]: 1 - Group 4: Nodes
[2, 3]: 2
Thus, the total interaction cost is 1 + 2 = 3.
Example 4:
Input: n = 2, edges = [[0,1]], group = [1,2]
Output: 0
Explanation:
All nodes belong to different groups and there are no valid pairs. Therefore, the total interaction cost is 0.
Constraints:
1 <= n <= 105edges.length == n - 1edges[i] = [ui, vi]0 <= ui, vi <= n - 1group.length == n1 <= group[i] <= n- The input is generated such that
edgesrepresents a valid tree.
Approach Overview
Problem Overview: Given a tree with nodes partitioned into groups, you need to find the total sum of interaction costs between all pairs of distinct groups, where the cost between two groups is defined as the sum of distances from every node in one group to every node in the other group.
Approach 1: Brute Force (O(n^2) time, O(n) space)
For each pair of groups, compute the sum of distances between all nodes in those groups by running BFS/DFS from each node in one group and summing distances to nodes in the other. This repeats work for every pair and every node, leading to quadratic complexity. It's straightforward but only feasible for small trees or few groups.
Approach 2: Edge Contribution with DFS (O(n) time, O(n) space)
The key insight is to count how many times each edge contributes to the total cost. For an edge connecting a subtree to the rest of the tree, it contributes exactly size_subtree * (total_nodes - size_subtree) times for each pair of nodes across that edge. To incorporate group costs, you need to track how many nodes from each group lie on each side of the edge. A single DFS computes subtree sizes and group counts per subtree, then you accumulate contributions for every edge. This reduces the problem to a single traversal and avoids pairwise enumeration.
Recommended for interviews: Interviewers expect the edge-contribution approach because it demonstrates deep understanding of tree properties and combinatorial counting. The brute force shows you can model the problem, but the optimal solution proves you can optimize using structural insights. Always start with brute force to clarify the logic, then pivot to the linear solution.
This problem builds on tree traversal and depth-first search, and also touches on combinatorics.
Solutions for this problem are being prepared.
Try solving it yourselfDetailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force (Pairwise BFS) | O(n^2) | O(n) | Small trees or when groups are few |
| Edge Contribution with DFS | O(n) | O(n) | General case and large inputs |
Frequently Asked Questions
Is Total Sum of Interaction Cost in Tree Groups II easy or hard?
Total Sum of Interaction Cost in Tree Groups II Python/Java solution
How to solve Total Sum of Interaction Cost in Tree Groups II in O(n)?
What is the best approach for Total Sum of Interaction Cost in Tree Groups II?
Is Total Sum of Interaction Cost in Tree Groups II asked at Google/Amazon/Meta?
What data structure is used in Total Sum of Interaction Cost in Tree Groups II?
What is the time complexity of Total Sum of Interaction Cost in Tree Groups II?
Ready to solve this problem?
Practice Total Sum of Interaction Cost in Tree Groups II with our built-in code editor and test cases.
Practice on FleetCodeProblem Info
Table of Contents
Practice this problem
Open in Editor