Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Tree
[[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]] 1
[[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]] 3
minimum-height-trees)sum-of-distances-in-tree)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3067: Count Pairs of Connectable Servers in a Weighted Tree Network
class Solution {
private int signalSpeed;
private List<int[]>[] g;
public int[] countPairsOfConnectableServers(int[][] edges, int signalSpeed) {
int n = edges.length + 1;
g = new List[n];
this.signalSpeed = signalSpeed;
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1], w = e[2];
g[a].add(new int[] {b, w});
g[b].add(new int[] {a, w});
}
int[] ans = new int[n];
for (int a = 0; a < n; ++a) {
int s = 0;
for (var e : g[a]) {
int b = e[0], w = e[1];
int t = dfs(b, a, w);
ans[a] += s * t;
s += t;
}
}
return ans;
}
private int dfs(int a, int fa, int ws) {
int cnt = ws % signalSpeed == 0 ? 1 : 0;
for (var e : g[a]) {
int b = e[0], w = e[1];
if (b != fa) {
cnt += dfs(b, a, ws + w);
}
}
return cnt;
}
}
// Accepted solution for LeetCode #3067: Count Pairs of Connectable Servers in a Weighted Tree Network
func countPairsOfConnectableServers(edges [][]int, signalSpeed int) []int {
n := len(edges) + 1
type pair struct{ x, w int }
g := make([][]pair, n)
for _, e := range edges {
a, b, w := e[0], e[1], e[2]
g[a] = append(g[a], pair{b, w})
g[b] = append(g[b], pair{a, w})
}
var dfs func(a, fa, ws int) int
dfs = func(a, fa, ws int) int {
cnt := 0
if ws%signalSpeed == 0 {
cnt++
}
for _, e := range g[a] {
b, w := e.x, e.w
if b != fa {
cnt += dfs(b, a, ws+w)
}
}
return cnt
}
ans := make([]int, n)
for a := 0; a < n; a++ {
s := 0
for _, e := range g[a] {
b, w := e.x, e.w
t := dfs(b, a, w)
ans[a] += s * t
s += t
}
}
return ans
}
# Accepted solution for LeetCode #3067: Count Pairs of Connectable Servers in a Weighted Tree Network
class Solution:
def countPairsOfConnectableServers(
self, edges: List[List[int]], signalSpeed: int
) -> List[int]:
def dfs(a: int, fa: int, ws: int) -> int:
cnt = 0 if ws % signalSpeed else 1
for b, w in g[a]:
if b != fa:
cnt += dfs(b, a, ws + w)
return cnt
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))
ans = [0] * n
for a in range(n):
s = 0
for b, w in g[a]:
t = dfs(b, a, w)
ans[a] += s * t
s += t
return ans
// Accepted solution for LeetCode #3067: Count Pairs of Connectable Servers in a Weighted Tree Network
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3067: Count Pairs of Connectable Servers in a Weighted Tree Network
// class Solution {
// private int signalSpeed;
// private List<int[]>[] g;
//
// public int[] countPairsOfConnectableServers(int[][] edges, int signalSpeed) {
// int n = edges.length + 1;
// g = new List[n];
// this.signalSpeed = signalSpeed;
// Arrays.setAll(g, k -> new ArrayList<>());
// for (var e : edges) {
// int a = e[0], b = e[1], w = e[2];
// g[a].add(new int[] {b, w});
// g[b].add(new int[] {a, w});
// }
// int[] ans = new int[n];
// for (int a = 0; a < n; ++a) {
// int s = 0;
// for (var e : g[a]) {
// int b = e[0], w = e[1];
// int t = dfs(b, a, w);
// ans[a] += s * t;
// s += t;
// }
// }
// return ans;
// }
//
// private int dfs(int a, int fa, int ws) {
// int cnt = ws % signalSpeed == 0 ? 1 : 0;
// for (var e : g[a]) {
// int b = e[0], w = e[1];
// if (b != fa) {
// cnt += dfs(b, a, ws + w);
// }
// }
// return cnt;
// }
// }
// Accepted solution for LeetCode #3067: Count Pairs of Connectable Servers in a Weighted Tree Network
function countPairsOfConnectableServers(edges: number[][], signalSpeed: number): number[] {
const n = edges.length + 1;
const g: [number, number][][] = Array.from({ length: n }, () => []);
for (const [a, b, w] of edges) {
g[a].push([b, w]);
g[b].push([a, w]);
}
const dfs = (a: number, fa: number, ws: number): number => {
let cnt = ws % signalSpeed === 0 ? 1 : 0;
for (const [b, w] of g[a]) {
if (b != fa) {
cnt += dfs(b, a, ws + w);
}
}
return cnt;
};
const ans: number[] = Array(n).fill(0);
for (let a = 0; a < n; ++a) {
let s = 0;
for (const [b, w] of g[a]) {
const t = dfs(b, a, w);
ans[a] += s * t;
s += t;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.