Graph Theory37 sections · 1633 units
Open in Course

Algorithm - Count Paths in Range

(Range query on distances)

1.1. Find centroid cc using the standard algorithm.

2.2. DFS from cc to get all distances.

For each distance dd, count distances in range [k1d,k2d][k_1 - d, k_2 - d] using a data structure that supports range queries.

3.3. Subtract pairs where both nodes are in the same child subtree using the same range-counting approach.

4.4. Recurse on components after removing cc.

Use a sorted list or balanced tree to count range matches efficiently in O(logn)O(\log n) per query.

Space complexity is O(n)O(n) for the data structures used.