Total Sum of Interaction Cost in Tree Groups II Problem
Description
LeetCode Problem 4018.
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] = [u_i, v_i] indicates an undirected edge between nodes u_i and v_i.
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 <= 10^5edges.length == n - 1edges[i] = [u_i, v_i]0 <= u_i, v_i <= n - 1group.length == n1 <= group[i] <= n- The input is generated such that
edgesrepresents a valid tree.
Solution
Approach: Edge Contribution + Small-to-Large Merging
In a tree each edge lies on the path between u and v exactly when it separates them. For a group g with T_g nodes, if c of them are below the edge, the edge is used by c * (T_g - c) pairs. So the answer is the sum, over every edge and every group, of c * (T_g - c).
Root the tree at 0 and process nodes in reverse BFS order, so a node is handled after all of its descendants. Each node keeps a map from group to the count in its subtree, and a value cost equal to the sum of c * (T_g - c) over its map. Before a node is merged into its parent, its cost is exactly the contribution of the edge above it, so add it to the answer.
To merge, keep the larger map and insert the entries of the smaller one, updating cost for each group that changes. Every entry moves O(log n) times, so the total work is O(n log n) map operations.
Complexity: time O(n log n), space O(n).
class Solution:
def interactionCosts(self, n: int, edges: List[List[int]], group: List[int]) -> int:
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
total = [0] * (n + 1)
for x in group:
total[x] += 1
# BFS order from the root: children always come after their parent
parent = [-1] * n
order = [0]
for u in order:
for v in g[u]:
if v != parent[u]:
parent[v] = u
order.append(v)
# cnt[v]: group -> number of nodes of that group in the subtree of v
# cost[v]: sum over groups of c * (total - c), the pairs the edge above v separates
cnt = [{group[i]: 1} for i in range(n)]
cost = [total[group[i]] - 1 for i in range(n)]
ans = 0
for v in reversed(order[1:]):
ans += cost[v]
p = parent[v]
if len(cnt[v]) > len(cnt[p]):
cnt[v], cnt[p] = cnt[p], cnt[v]
cost[v], cost[p] = cost[p], cost[v]
big = cnt[p]
for x, c in cnt[v].items():
cur = big.get(x, 0)
cost[p] -= cur * (total[x] - cur)
cur += c
cost[p] += cur * (total[x] - cur)
big[x] = cur
cnt[v] = None
return ans