Count Pairs of Connectable Servers in a Weighted Tree Network - Problem

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 a and the path from c to b 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.

Input & Output

Example 1 — Basic Tree Network
$ Input: edges = [[0,1,1],[1,2,5],[2,3,13],[1,4,9],[4,5,2]], signalSpeed = 1
Output: [0,4,0,0,0,0]
💡 Note: With signalSpeed=1, all distances are valid. Server 1 can connect 4 pairs through its central position in the tree structure.
Example 2 — Specific Signal Speed
$ Input: edges = [[0,6,3],[6,4,2],[6,3,3],[4,5,2],[4,1,4],[4,2,1]], signalSpeed = 3
Output: [0,0,0,0,0,0,2]
💡 Note: Only server 6 can act as a hub. Distances must be divisible by 3, creating 2 valid pairs through server 6.
Example 3 — Linear Chain
$ Input: edges = [[0,1,2],[1,2,4]], signalSpeed = 2
Output: [0,1,0]
💡 Note: In a 3-node linear chain, only the middle server (1) can connect the endpoints since both distances are divisible by 2.

Constraints

  • 1 ≤ n ≤ 1000
  • edges.length == n - 1
  • 1 ≤ ai, bi ≤ n - 1
  • ai != bi
  • 1 ≤ weighti ≤ 106
  • 1 ≤ signalSpeed ≤ 106
  • The input represents a valid tree

Visualization

Tap to expand
Tree Network: Finding Connectable Server PairsInput: edges=[[0,1,6],[0,2,3],[0,3,4]], signalSpeed=30123634Server 0 as hub:Distance to 1: 6 (÷3 = 2 ✓)Distance to 2: 3 (÷3 = 1 ✓)Distance to 3: 4 (÷3 ≠ integer ✗)Valid pairs through 0: (1,2)Output: [1,0,0,0]Only server 0 can connect exactly 1 pair of servers
Understanding the Visualization
1
Input
Tree network with weighted edges and signalSpeed requirement
2
Process
For each server as hub, count valid distance pairs to other servers
3
Output
Array showing connectable pairs count for each server as hub
Key Takeaway
🎯 Key Insight: In trees, paths from a central node to different subtrees never overlap, making pair counting efficient through DFS subtree exploration
Asked in
Meta 12 Google 8 Amazon 6
8.9K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen