#3786

Total Sum of Interaction Cost in Tree Groups

Hard
ArrayTreeDepth-First SearchHash MapArray
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)

Use DFS to count nodes in each subtree for each group. For each edge, calculate the contribution to the interaction cost based on the number of nodes in the subtrees.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build the tree from edges and perform a DFS to count nodes in each group for each subtree.
  2. 2Step 2: For each edge, calculate the contribution as subtree_count * (total_count - subtree_count).
  3. 3Step 3: Sum all contributions to get the total interaction cost.
solution.py22 lines
1def total_interaction_cost(n, edges, group):
2    from collections import defaultdict
3    graph = defaultdict(list)
4    for u, v in edges:
5        graph[u].append(v)
6        graph[v].append(u)
7    group_count = defaultdict(int)
8    visited = [False] * n
9    total_cost = 0
10    def dfs(node):
11        nonlocal total_cost
12        visited[node] = True
13        count = 1
14        for neighbor in graph[node]:
15            if not visited[neighbor]:
16                subtree_count = dfs(neighbor)
17                total_cost += subtree_count * (group_count[group[node]] - subtree_count)
18                count += subtree_count
19        group_count[group[node]] += count
20        return count
21    dfs(0)
22    return total_cost

Complexity note: The DFS traverses each node once, leading to linear time complexity, while storing counts requires O(n) space.

  • 1Count nodes in each group efficiently using DFS.
  • 2Understand how paths in trees relate to edge contributions.

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