LeetCode solutions

3326. Count Pairs of Connectable Servers in a Weighted Tree Network

My accepted Python solution to LeetCode problem 3326, Count Pairs of Connectable Servers in a Weighted Tree Network, running in 1575ms.

  • Difficulty: Medium
  • Python
  • Runtime 1575ms
  • Memory 19.4MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 1575ms, memory 19.4MB, accepted 2025-12-31.

python
class Solution:
    def countPairsOfConnectableServers(self, edges: List[List[int]], signalSpeed: int) -> List[int]:
        from collections import defaultdict
        
        n = len(edges) + 1
        graph = defaultdict(list)
        
        for a, b, w in edges:
            graph[a].append((b, w))
            graph[b].append((a, w))
        
        def dfs(node, parent, dist):
            count = 1 if dist % signalSpeed == 0 else 0
            for neighbor, weight in graph[node]:
                if neighbor != parent:
                    count += dfs(neighbor, node, dist + weight)
            return count
        
        result = []
        for server in range(n):
            counts = []
            for neighbor, weight in graph[server]:
                count = dfs(neighbor, server, weight)
                counts.append(count)
            
            # Count pairs from different subtrees
            pairs = 0
            total = 0
            for c in counts:
                pairs += total * c
                total += c
            result.append(pairs)
        
        return result

Source