Centroid Decomposition - Problem
Centroid decomposition is a powerful technique used to analyze tree structures by recursively finding and removing centroids. A centroid of a tree is a node whose removal results in no subtree having more than n/2 nodes, where n is the total number of nodes.
Given a tree with n nodes (numbered from 0 to n-1) represented as an edge list, perform centroid decomposition and use it to efficiently answer distance queries between pairs of nodes.
Your task is to:
- Build the centroid decomposition tree
- Preprocess distances from each centroid to all nodes in its subtree
- Answer distance queries in
O(log n)time
Input: An array of edges representing the tree, followed by an array of query pairs.
Output: An array containing the shortest distance between each queried pair of nodes.
Input & Output
Example 1 — Basic Linear Tree
$
Input:
edges = [[0,1],[1,2],[2,3]], queries = [[0,3],[1,2]]
›
Output:
[3,1]
💡 Note:
For query (0,3): path 0→1→2→3 has distance 3. For query (1,2): direct edge 1→2 has distance 1.
Example 2 — Star Tree
$
Input:
edges = [[1,0],[1,2],[1,3],[1,4]], queries = [[0,4],[2,3]]
›
Output:
[2,2]
💡 Note:
For query (0,4): path 0→1→4 has distance 2. For query (2,3): path 2→1→3 has distance 2.
Example 3 — Same Node Query
$
Input:
edges = [[0,1],[1,2]], queries = [[1,1],[0,2]]
›
Output:
[0,2]
💡 Note:
Query (1,1): same node has distance 0. Query (0,2): path 0→1→2 has distance 2.
Constraints
- 1 ≤ n ≤ 104
- edges.length = n - 1
- 0 ≤ edges[i][0], edges[i][1] < n
- 1 ≤ queries.length ≤ 104
- 0 ≤ queries[i][0], queries[i][1] < n
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code