You are given an unrooted weighted tree with n vertices representing servers numbered from 0 to n - 1, an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional edge between vertices ai and bi of weight weighti. You are also given an integer signalSpeed.
Two servers a and b are connectable through a server c if:
a < b, a != c and b != c.c to a is divisible by signalSpeed.c to b is divisible by signalSpeed.c to b and the path from c to a do not share any edges.Return an integer array count of length n where count[i] is the number of server pairs that are connectable through the server i.
Example 1:
Input: edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1 Output: [0,4,6,6,4,0] Explanation: Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges. In the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.
Example 2:
Input: edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3 Output: [2,0,0,0,0,0,2] Explanation: Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6). Through server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5). It can be shown that no two servers are connectable through servers other than 0 and 6.
Constraints:
2 <= n <= 1000edges.length == n - 1edges[i].length == 30 <= ai, bi < nedges[i] = [ai, bi, weighti]1 <= weighti <= 1061 <= signalSpeed <= 106edges represents a valid tree.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a map of cities connected by roads of different lengths, and you want to find how many pairs of cities can communicate through a third central city such that the travel times to that central city are multiples of a specific number. The brute force approach involves testing every single city as the central meeting point and checking every possible pair of other cities to see if they meet the travel time requirement.
Here's how the algorithm would work step-by-step:
class Solution:
def countOfPairsOfConnectableServers(self, edge_list: list[list[int]], signal_speed: int) -> list[int]:
total_nodes = len(edge_list) + 1
adjacency_list = [[] for _ in range(total_nodes)]
for node_u, node_v, weight in edge_list:
adjacency_list[node_u].append((node_v, weight))
adjacency_list[node_v].append((node_u, weight))
def explore_subtree(current_node, parent_node, current_distance, remainder_counts):
if current_distance % signal_speed == 0:
remainder_counts[0] += 1
for neighbor_node, edge_weight in adjacency_list[current_node]:
if neighbor_node != parent_node:
explore_subtree(neighbor_node, current_node, current_distance + edge_weight, remainder_counts)
connectable_pairs_result = [0] * total_nodes
# Iterate through every node to treat it as the central meeting point in the tree for central_node in range(total_nodes):
accumulated_valid_pairs = 0
previous_branch_nodes = 0
for neighbor_node, edge_weight in adjacency_list[central_node]:
branch_remainders = [0]
explore_subtree(neighbor_node, central_node, edge_weight, branch_remainders)
current_branch_count = branch_remainders[0]
accumulated_valid_pairs += previous_branch_nodes * current_branch_count
previous_branch_nodes += current_branch_count
connectable_pairs_result[central_node] = accumulated_valid_pairs
# Return the final calculated list of valid connectable pairs for every server node return connectable_pairs_resultInstead of checking every possible pair of servers from scratch, which takes too much time, we can pick each server as a central meeting point one by one. From that chosen server, we look down its different connecting paths and count how many servers can reach it with a travel time that is a multiple of a given target number.
Here's how the algorithm would work step-by-step:
class Solution:
def count_pairs_of_connectable_servers(self, edge_list: list[list[int]], signal_speed: int) -> list[int]:
total_servers = len(edge_list) + 1
adjacency_list = [[] for _ in range(total_servers)]
for server_u, server_v, weight in edge_list:
adjacency_list[server_u].append((server_v, weight))
adjacency_list[server_v].append((server_u, weight))
def count_divisible_nodes(current_node: int, parent_node: int, current_distance: int) -> int:
node_count = 1 if current_distance % signal_speed == 0 else 0
for neighbor_node, edge_weight in adjacency_list[current_node]:
if neighbor_node != parent_node:
node_count += count_divisible_nodes(neighbor_node, current_node, current_distance + edge_weight)
return node_count
connectable_pairs_result = [0] * total_servers
# We iterate through each server to treat it as the central meeting point independently.
for central_server in range(total_servers):
accumulated_valid_servers = 0
for neighbor_node, edge_weight in adjacency_list[central_server]:
valid_nodes_in_branch = count_divisible_nodes(neighbor_node, central_server, edge_weight)
connectable_pairs_result[central_server] += accumulated_valid_servers * valid_nodes_in_branch
accumulated_valid_servers += valid_nodes_in_branch
# This optimization avoids redundant pair calculations by aggregating neighborhood results.
return connectable_pairs_result| Case | How to Handle |
|---|---|
| Minimum tree size with fewer than three nodes | Return an array of zeros since a connecting middle server requires at least two distinct branches which is impossible with less than three nodes. |
| Line graph or star graph topologies leading to highly skewed distributions | Efficiently compute path modular arithmetic using depth-first search or breadth-first search to aggregate branch remainders without generating redundant paths. |
| Edge weights that are zero | Treat zero-weight edges normally as valid path components since their accumulated sum will still correctly evaluate against the distance factor modulus. |
| Distance factor of one | Ensure all path weight sums modulo one evaluate to zero so every pair of branches from a central server becomes connectable. |
| No valid pairs found for any server | Return an array of zeros matching the number of nodes because no branches meet the modulo distance factor requirement. |
| Deep recursion depth on a skewed linear tree | Iterative graph traversal or language stack limit adjustments should be used to prevent stack overflow errors during depth-first search. |
| Large edge weights causing integer overflow | Accumulate path weights using modulo arithmetic relative to the distance factor at each step to keep numbers within standard integer bounds. |
| Maximum-sized tree inputs up to one thousand nodes | Compute branch remainders independently for each neighbor of every node to achieve an optimal overall time complexity. |