Heavy-Light Decomposition - Problem

Implement heavy-light decomposition on a tree to answer path queries efficiently in O(log² n) time complexity.

Given a tree with n nodes, you need to:

1. Build the heavy-light decomposition structure

2. Handle path queries from node u to node v

3. Return the sum of values along the path

The tree is represented as an adjacency list where edges[i] = [parent, child] indicates an edge between parent and child nodes. Node values are given in the values array where values[i] is the value of node i.

Path Query: Find the sum of all node values from node u to node v in the tree.

Input & Output

Example 1 — Simple Path Query
$ Input: edges = [[0,1],[1,2],[1,3],[3,4]], values = [1,2,3,4,5], u = 0, v = 4
Output: 12
💡 Note: Path from node 0 to node 4: 0 → 1 → 3 → 4. Sum = values[0] + values[1] + values[3] + values[4] = 1 + 2 + 4 + 5 = 12
Example 2 — Different Path
$ Input: edges = [[0,1],[1,2],[1,3]], values = [5,10,15,20], u = 2, v = 3
Output: 45
💡 Note: Path from node 2 to node 3: 2 → 1 → 3. Sum = values[2] + values[1] + values[3] = 15 + 10 + 20 = 45
Example 3 — Single Node Path
$ Input: edges = [[0,1],[1,2]], values = [7,8,9], u = 1, v = 1
Output: 8
💡 Note: Path from node 1 to itself contains only node 1. Sum = values[1] = 8

Constraints

  • 2 ≤ n ≤ 104
  • edges.length = n - 1
  • -106 ≤ values[i] ≤ 106
  • 0 ≤ u, v < n

Visualization

Tap to expand
INPUT TREEALGORITHMRESULT0val=11val=22val=33val=44val=5Query: u=0, v=4Path: 0→1→3→41Heavy-Light Split2Build Chains3Segment Trees4Path QueryHeavy Chain A[0,1,3,4] → SegTreeTime: O(log² n)Space: O(n log n)Queries: Very Fast!Path Sum121+2+4+5✓ Efficient O(log² n)✓ Handles multiple queries✓ Works for any tree pathvs Brute Force O(n):100x faster on large trees!Key Insight:Heavy-light decomposition splits any tree path into O(log n) chain segments.Using segment trees on each chain enables O(log n) range queries per segment,achieving O(log² n) total time - exponentially faster than O(n) brute force!TutorialsPoint - Heavy-Light Decomposition | Advanced Tree Algorithm
Asked in
Google 15 Facebook 8 Microsoft 12 Amazon 6
8.9K Views
Low Frequency
~45 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