#3067
Count Pairs of Connectable Servers in a Weighted Tree Network
MediumArrayTreeDepth-First SearchDepth-First SearchTree TraversalDynamic Programming on Trees
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses Depth-First Search (DFS) to count the number of nodes in each subtree that are at distances divisible by signalSpeed. This avoids redundant calculations and efficiently counts connectable pairs.
⚙️
Algorithm
4 steps- 1Step 1: Build the tree from the edges.
- 2Step 2: For each server c, run DFS to count nodes in its subtree whose distances from c are divisible by signalSpeed.
- 3Step 3: For each child of c, calculate the number of connectable pairs using the formula: ((S - num[c_i]) * num[c_i]) / 2, where S is the total count of nodes in the subtree.
- 4Step 4: Store the result for each server.
solution.py34 lines
1# Full working Python code
2from collections import defaultdict
3
4def countPairsOptimal(edges, signalSpeed):
5 n = len(edges) + 1
6 graph = defaultdict(list)
7 for a, b, weight in edges:
8 graph[a].append((b, weight))
9 graph[b].append((a, weight))
10
11 count = [0] * n
12 subtree_count = [0] * n
13
14 def dfs(node, parent, depth):
15 total = 1
16 for neighbor, weight in graph[node]:
17 if neighbor != parent:
18 child_count = dfs(neighbor, node, depth + weight)
19 if (depth + weight) % signalSpeed == 0:
20 count[node] += child_count
21 total += child_count
22 subtree_count[node] = total
23 return total
24
25 dfs(0, -1, 0)
26
27 for c in range(n):
28 total_pairs = 0
29 for neighbor, weight in graph[c]:
30 if subtree_count[neighbor] > 0:
31 total_pairs += (subtree_count[c] - subtree_count[neighbor]) * subtree_count[neighbor]
32 count[c] += total_pairs // 2
33
34 return countℹ
Complexity note: The time complexity is O(n) because we traverse each node once during the DFS. The space complexity is O(n) due to the storage of the graph and subtree counts.
- 1Understanding the structure of trees is crucial for efficiently solving problems related to them.
- 2Using DFS allows us to gather necessary information about the tree in a single traversal, reducing redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.