Taro Logo

Count Pairs of Connectable Servers in a Weighted Tree Network

Medium
Asked by:
Profile picture
Profile picture
5 views
Topics:
TreesGraphsRecursion

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.
  • The distance from c to a is divisible by signalSpeed.
  • The distance from c to b is divisible by signalSpeed.
  • The path from 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 <= 1000
  • edges.length == n - 1
  • edges[i].length == 3
  • 0 <= ai, bi < n
  • edges[i] = [ai, bi, weighti]
  • 1 <= weighti <= 106
  • 1 <= signalSpeed <= 106
  • The input is generated such that edges represents a valid tree.

Solution


Clarifying Questions

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:

  1. What are the constraints on the number of nodes (servers) in the tree and the maximum weight of the edges?
  2. Can edge weights be negative, or are they guaranteed to be non-negative integers?
  3. When considering pairs of servers $(A, B)$ connected through a middle server $C$, does the order of the pair matter (i.e., are $(A, B)$ and $(B, A)$ considered the same pair), and can $A$ and $B$ be the same server?
  4. If a server has fewer than two distinct subtrees (or branches), meaning it's impossible to form a pair of disjoint paths, should its count simply be zero?
  5. Should the returned array be ordered such that the $i$-th element corresponds to the number of connectable pairs with server $i$ as the connecting point?

Brute Force Solution

Approach

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:

  1. Pick one city on the map to act as your starting point for testing.
  2. Look at all the other cities and group them based on the paths leading away from your starting point.
  3. Take every possible pair of cities from different groups.
  4. Calculate the total travel time from the first city in the pair to your starting point, and from your starting point to the second city in the pair.
  5. Check if both of these travel times can be evenly divided by the target number you were given.
  6. If both travel times are exact multiples of the target number, count this as a valid pair.
  7. Repeat this checking process for every possible pair of cities using the current starting point.
  8. Once you have checked all pairs for the current starting point, write down the total count of valid pairs for that specific city.
  9. Finally, move on to the next city on the map, treat it as your new starting point, and repeat the entire process from the beginning until every city has had a turn as the central meeting point.

Code Implementation

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_result

Big(O) Analysis

Time Complexity
O(n²) – For each of the n nodes in the tree acting as the central meeting point, we must inspect its adjacent branches and compute path weights to all connected nodes using a depth-first search or recursive traversal. When combining pairs of nodes from different branches, the total pair-checking work across all branches for a single starting node is proportional to the square of the degree of that node, or more generally bounded by the total number of nodes n. Repeating this independent pair-counting process for all n possible starting nodes yields approximately n times n operations. This leads to n squared operations overall, which simplifies to the final Big O time complexity of O(n²).
Space Complexity
O(N) – The auxiliary space is dominated by the recursion stack used during depth-first search traversals from each central city, which can reach a maximum depth of N where N is the total number of cities in the tree network. Additionally, temporary variables and lists are used to group neighbor branches and track path weights from the current starting city, but these scale linearly. Therefore, the total extra memory consumed by the algorithm grows proportionally to the number of nodes N, simplifying to Big O of N.

Optimal Solution

Approach

Instead 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:

  1. Choose a starting server to act as our current meeting point.
  2. Look at all the direct paths leading away from this meeting server into different neighborhoods of the network.
  3. For each separate neighborhood, walk down all the connected paths and count how many servers can reach the meeting point with a total travel time that divides evenly by our target number.
  4. Keep a running total of the valid servers found in each neighborhood as we explore them one by one.
  5. When looking at any new neighborhood, multiply the number of valid servers we just found in this neighborhood by the total number of valid servers we already found in all previous neighborhoods combined, and add this product to our overall count of connectable pairs.
  6. Add the newly explored neighborhood's valid servers to our running collection and move on to the next neighborhood.
  7. Once all neighborhoods connected to the current meeting server are checked, record the final pair count for this server and repeat the entire process by choosing the next server as our meeting point.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n²) – For each of the n servers chosen in turn as the central meeting point, we traverse the attached subtrees to count valid servers whose distances are multiples of the target. Although each depth-first search visits every edge in the tree, summing these traversal costs across all n potential meeting points results in total operations proportional to n * n. This quadratic workload simplifies to O(n²) time complexity.
Space Complexity
O(n) – The auxiliary space is driven by the recursive calls of the depth-first search exploring the tree from each chosen meeting server, which can reach a maximum recursion depth of n in a skewed tree. Additionally, the adjacency list representing the weighted tree network stores n minus one edges, contributing linearly to the overall extra memory. Variables used for counting valid servers and running totals require only a constant amount of auxiliary space. As the input size n grows, the maximum stack depth and graph storage scale directly, resulting in a linear space complexity of O(n).

Edge Cases

Minimum tree size with fewer than three nodes
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Compute branch remainders independently for each neighbor of every node to achieve an optimal overall time complexity.