MediumArrayTreeDepth-First SearchUpdated Sep 2026

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

Asked at Rippling

Difficulty

Medium

Time

O(n^2)

Space

O(n)

Pattern

Array

Companies

1

Problem

You are given an unrooted weighted tree with n servers, numbered 0 to n-1. Each edge [a, b, w] connects server a and server b and has a positive weight w. You are also given an integer signalSpeed.

Two servers a and b are connectable through a third server c when all of these hold: a < b, neither a nor b equals c, the distance from c to a is divisible by signalSpeed, the distance from c to b is divisible by signalSpeed, and the two paths c → a and c → b share no edges. The last rule means a and b must lie in two different branches hanging off c.

Return an array count of length n, where count[i] is the number of connectable pairs through server i.

A useful way to think about it: for a fixed center c, cut c out of the tree. The tree splits into one separate piece per neighbor of c. A valid pair must take one server from one piece and the other server from a different piece, and both distances measured from c must be multiples of signalSpeed.

Pairs must come from different branches

2dist 113dist 40dist 3Center 1 with signalSpeed = 2: distances 3, 1, 4 fromthe center3 mod 2 = 11 mod 2 = 14 mod 2 = 0only (0, 2) sums to an even number
Cutting out center 1 leaves three branches; a valid pair takes one server from each of two different branches.

Constraints

  • ●2 <= n <= 1000
  • ●edges.length == n - 1
  • ●edges[i].length == 3
  • ●0 <= ai, bi < n
  • ●1 <= weighti <= 10^6
  • ●1 <= signalSpeed <= 10^6
  • ●The input is generated such that edges represents a valid tree.

Examples

Example 1
Inputedges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1
Output[0,4,6,6,4,0]
WhyThe tree is a straight line 0-1-2-3-4-5. Since signalSpeed is 1, every distance is divisible by it, so only the different-branch rule matters. For center 2, the left side has servers 0 and 1, the right side has 3, 4 and 5, giving 2 × 3 = 6 pairs. The two end servers have only one branch, so they get
Example 2
Inputedges = [[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]
WhyThrough server 0 the branches are {6,5} with distances 3 and 6, and {3,2,1,4} with distances 1, 8, 7, 3. Only distance 3 (server 4) is divisible by 3 on that side, and it pairs with both 5 and 6 on the other side, giving 2 pairs. Server 6 is symmetric and also gets 2. Every other center has at most
Example 3
Inputedges = [[0,1,3],[1,2,1],[1,3,4]], signalSpeed = 2
Output[0,1,0,0]
WhyCenter 1 has three branches: server 0 at distance 3, server 2 at distance 1, server 3 at distance 4. Distances 3 and 1 are odd, 4 is even. A pair needs remainders that add to an even number, so only (0, 2) works — both odd. That is 1 pair. Centers 0, 2 and 3 each have a single branch, so they get 0.

Asked At

1 companies
CompanyDifficulty
RipplingMediumView all Rippling questions →

How to Think About It

1

For each center server i, remove i to get a forest of subtrees. For each subtree, collect the distances from i to every node in that subtree, modulo signalSpeed.

2

Two nodes a and b are connectable through i if they are in different subtrees (different first-edge branches from i) and (dist(i,a) + dist(i,b)) % signalSpeed == 0.

3

Efficient counting: for each subtree, maintain a frequency array of (distance % signalSpeed). For each new subtree, count pairs with already-seen subtrees using the complement: seen[(signalSpeed - r) % signalSpeed] gives the count of nodes in previous subtrees where adding this node makes the sum divisible.

4

Algorithm for each center: DFS into each neighbor branch to collect distance mods. For each branch, count cross-branch pairs using the complement formula, then merge the branch into the seen set.

5

Total complexity: O(n^2) because for each of n centers, we do O(n) work (DFS + pair counting). This is acceptable since n <= 1000.

Optimal Approach

Step 1: Build adjacency list for the tree.
Step 2: For each server i (center):
a. For each neighbor j of i, DFS through j to collect distances from i. Build a frequency array of (distance % signalSpeed).
b. For each new subtree, count cross-branch pairs: for each remainder r in the subtree, add seen[(signalSpeed - r) % signalSpeed] to the answer.
c. Merge the subtree frequencies into the running seen set.
Step 3: Return the answers array.

Walkthrough for n=4, edges=[[0,1,3],[1,2,1],[1,3,4]], signalSpeed=2:

  • Center 1: DFS into 0 (dist=3, mod=1), 2 (dist=1, mod=1), 3 (dist=4, mod=0).
    • Subtree 0: mod 1 count=1. Pairs with seen: seen[1]=0. Total=0. Merge: seen[1]=1.
    • Subtree 2: mod 1 count=1. Pairs with seen: seen[1]=1. Total+=1. Merge: seen[1]=2.
    • Subtree 3: mod 0 count=1. Pairs with seen: seen[0]=0. Total+=0. Merge: seen[0]=1.
    • Answer[1] = 1.
  • Center 0: one subtree (via 1). No cross-branch pairs. Answer[0] = 0.
  • Similarly for centers 2 and 3: answer = [0,1,0,0].

Time: O(n^2) - for each center, DFS is O(n) and pair counting is O(n). Space: O(n) for DFS recursion and frequency arrays.

Count per branch, then merge

branch 0r=0r=101Branch of server 0: one node with remainder 1seenr=0r=101After merging: seen[1] = 1branch 2r=0r=101Branch of server 2: remainder 1, so it pairs withseen[(2-1)%2] = seen[1] = 1for each remainder r:ans += cnt[r] * seen[(S - r) % S]then seen[r] += cnt[r]
For each branch we count remainders, pair them against everything seen so far, then merge the branch into the seen set.
ComplexityTime O(n^2)Space O(n)For each of the n centers we walk the whole tree once and scan the remainder array, so the cost is n times O(n); the extra space is the DFS stack plus one frequency array of size signalSpeed.

What Trips People Up in Real Interviews

1

Counting pairs within the same subtree. Connectable pairs must be in DIFFERENT subtrees (different first-edge branches from i).

2

Forgetting that the tree is weighted. Distances are accumulated edge weights, not just hop counts. Use the actual weight when computing dist(i, child).

3

Wrong modular arithmetic. (dist_a + dist_b) % s == 0 means dist_a % s and dist_b % s are complements: (r_a + r_b) % s == 0.

4

Missing that the result is an array, not a single number. Each server i gets its own count of connectable pairs.

5

Double-counting pairs. Each pair (a,b) is counted once when processing center i. Do not count (a,b) and (b,a) separately.

Solution Code

O(n^2) time
class Solution:
    def countPairsOfConnectableServers(self, edges, signalSpeed):
        n = len(edges) + 1
        g = [[] for _ in range(n)]
        for a, b, w in edges:
            g[a].append((b, w))
            g[b].append((a, w))

        def branch_counts(center):
            counts = []
            for v, w in g[center]:
                cnt = [0] * signalSpeed
                stack = [(v, center, w)]
                while stack:
                    u, p, d = stack.pop()
                    cnt[d % signalSpeed] += 1
                    for nb, ww in g[u]:
                        if nb != p:
                            stack.append((nb, u, d + ww))
                counts.append(cnt)
            return counts

        ans = [0] * n
        for c in range(n):
            seen = [0] * signalSpeed
            for cnt in branch_counts(c):
                for r in range(signalSpeed):
                    ans[c] += cnt[r] * seen[(signalSpeed - r) % signalSpeed]
                for r in range(signalSpeed):
                    seen[r] += cnt[r]
        return ans

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Count Pairs of Connectable Servers in a Weighted Tree Network problem?

Given a weighted tree with n servers (0 to n-1) and edges [a, b, weight], count for each server i the number of pairs (a, b) where a and b are in different branches of i, and the combined distance from i to a and i to b is divisible by signalSpeed.

How do you solve Count Pairs of Connectable Servers in a Weighted Tree Network?

The optimal approach runs in O(n^2) time and O(n) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Count Pairs of Connectable Servers in a Weighted Tree Network?

Count Pairs of Connectable Servers in a Weighted Tree Network is asked at Rippling. It is a medium difficulty problem.

What are common mistakes on Count Pairs of Connectable Servers in a Weighted Tree Network?
  • Counting pairs within the same subtree. Connectable pairs must be in DIFFERENT subtrees (different first-edge branches from i).
  • Forgetting that the tree is weighted. Distances are accumulated edge weights, not just hop counts. Use the actual weight when computing dist(i, child).
  • Wrong modular arithmetic. (dist_a + dist_b) % s == 0 means dist_a % s and dist_b % s are complements: (r_a + r_b) % s == 0.
  • Missing that the result is an array, not a single number. Each server i gets its own count of connectable pairs.
  • Double-counting pairs. Each pair (a,b) is counted once when processing center i. Do not count (a,b) and (b,a) separately.