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:

  1. Build the centroid decomposition tree
  2. Preprocess distances from each centroid to all nodes in its subtree
  3. 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
INPUTALGORITHMRESULT0123Tree: 0-1-2 | 3Queries:Distance(0,3) = ?Distance(1,2) = ?1FindCentroid2Build3Centroid Tree4PreprocessDistancesResults[3, 1]Query (0,3): 3Query (1,2): 1Time: O(log n) per queryafter O(n log n) preprocessingKey Insight:Centroid decomposition creates a balanced tree structure where any distance querycan be answered in O(log n) time by finding the LCA in the centroid tree.TutorialsPoint - Centroid Decomposition | Advanced Tree Algorithm
Asked in
Google 25 Meta 18 Amazon 15 Microsoft 12
12.0K Views
Low Frequency
~45 min Avg. Time
450 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