AlgoTales · Roadmap

Heavy-Light Decomposition

Advanced · 13 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Heavy-light decomposition splits a tree into a few long straight "highways" so that any path between two nodes crosses only a few highways. Each highway can then be queried like an ordinary list, which is much easier and faster.

Practical use cases

  • Web app: Slowest link on a network route. A network-admin dashboard shows the slowest connection on the route between two offices in a tree-shaped network. Walking every link on the path is slow for big networks. With highways, the route is covered by a few chunks, each checked by a fast range lookup. A route across a network of 100,000 links is answered in a few highway checks, not a full walk.
  • Web app: Org-chart analytics. An HR tool wants the total budget along the chain from one employee up to another, with budgets changing during the day. Highways allow fast updates and fast chain totals together. Budget changes and chain totals both stay fast, so the chart updates as the user edits.
  • Web app: Category tree stock totals. A shop with a deep category tree needs the stock total along a path of categories while stock changes. A few highway range queries give the answer instantly. Updates to stock and path totals both finish immediately, even for a very deep category tree.
  • System: Network trees and contest problems. Telecom trees and programming contests use this to run path queries, with updates, without scanning the path link by link. Queries stay quick even on trees with hundreds of thousands of nodes.

The story: The Highways of Chaiwala Town

Chaiwala Town was a tree of lanes: one main road, lanes branching off it, little galis branching off those. The delivery boy, Kabir, got orders like "How many cups were sold on the way from stall 7 to stall 9?" The honest way was to walk every lane, adding as he went. With 100,000 stalls that took forever.

The mayor said, "Let us build highways!" At every junction, they looked at which branch carried the most stalls. That branch got a smooth heavy road continuing straight on. The smaller branches stayed as ordinary galis.

Surprise: no matter which two stalls you pick, the walk between them crosses only a few galis, because each time you leave a heavy road for a gali, the crowd below you at least halves. And along a highway, you can add the whole stretch in one move using a prefix-sum list.

Splitting a tree into heavy highways and light galis is called heavy-light decomposition.

How to spot this problem, and where you need it

You have a tree where values change and you must repeatedly get a total, maximum or minimum along the path between two nodes, and walking the path node by node is too slow.

Signs you need it

  • Queries sound like "maximum on the path from A to B" and values on nodes or edges change between queries.
  • Your path loop is fine for small trees but a 100,000-node tree makes it crawl.
  • The tree is unbalanced, with long chains, so simple tricks for balanced trees do not help.

Where to use it in a project

  • Network or infrastructure maps shaped like trees, where the weakest link on a route is needed.
  • Org charts or category trees where values keep changing and path totals are asked often.
  • Dependency trees where a summary along a path is needed many times a minute.

The solution

For each node, find the child with the biggest subtree (the heavy child) and link it to its parent, forming long chains. Number nodes so each chain is a continuous block in an array, and put a range structure (one that answers range questions quickly) over that array. For a path query, repeatedly jump up chain by chain, querying each chain's part, until both ends sit on the same chain, then finish there.

Payoff: Before: walking up to 100,000 nodes per question. After: a few chain jumps, each a quick range lookup.

Explain it like I am 8

Imagine a tree with a thick trunk and thin branches. Paint the thickest path from the roots up in red. Walking from any leaf to another, you will mostly walk along red paths and only hop onto thin branches a few times.

How it works, step by step

  1. Compute sizes: for every node count the nodes in its subtree.
  2. Pick the heavy child: each node chooses the child with the largest size. The edge to it is heavy; all other edges are light.
  3. Chains: follow heavy edges to make chains. Remember each node's head (top of its chain) and give nodes numbers so every chain is a consecutive range.
  4. Path query: while the two nodes are on different chains, take the stretch from the deeper chain's head down to its node, then jump to the head's parent.
  5. When both nodes are on the same chain, take the last stretch between them. Only about log n hops are ever needed.

The code in four languages

PHP

<?php
// Heavy-Light Decomposition with path sums (static values, prefix sums over chains).
class HLD {
    public array $parent, $depth, $size, $heavy, $head, $pos, $prefix;
    private array $adj;
    private int $cur = 0;

    function __construct(int $n, array $edges, array $val) {     // nodes are 1..n
        $this->adj = array_fill(0, $n + 1, []);
        foreach ($edges as [$a, $b]) { $this->adj[$a][] = $b; $this->adj[$b][] = $a; }
        $z = array_fill(0, $n + 1, 0);
        $this->parent = $this->depth = $this->size = $this->heavy = $this->head = $this->pos = $z;
        $this->dfs1(1, 0);
        $this->dfs2(1, 1);
        $line = array_fill(0, $n, 0);
        for ($v = 1; $v <= $n; $v++) $line[$this->pos[$v]] = $val[$v];   // values in chain order
        $this->prefix = [0];
        foreach ($line as $x) $this->prefix[] = end($this->prefix) + $x;
    }

    private function dfs1(int $u, int $p): void {
        $this->size[$u] = 1;
        foreach ($this->adj[$u] as $v) {
            if ($v === $p) continue;
            $this->parent[$v] = $u;
            $this->depth[$v] = $this->depth[$u] + 1;
            $this->dfs1($v, $u);
            $this->size[$u] += $this->size[$v];
            if ($this->heavy[$u] === 0 || $this->size[$v] > $this->size[$this->heavy[$u]]) $this->heavy[$u] = $v;
        }
    }

    private function dfs2(int $u, int $h): void {
        $this->head[$u] = $h;
        $this->pos[$u] = $this->cur++;
        if ($this->heavy[$u]) $this->dfs2($this->heavy[$u], $h);          // heavy child continues the chain
        foreach ($this->adj[$u] as $v) {
            if ($v !== $this->parent[$u] && $v !== $this->heavy[$u]) $this->dfs2($v, $v);   // light child starts a new chain
        }
    }

    private function range(int $l, int $r): int { return $this->prefix[$r + 1] - $this->prefix[$l]; }

    // Sum of values on the path u..v, plus how many chain blocks were used.
    function pathSum(int $u, int $v): array {
        $sum = 0; $blocks = 0;
        while ($this->head[$u] !== $this->head[$v]) {
            if ($this->depth[$this->head[$u]] < $this->depth[$this->head[$v]]) [$u, $v] = [$v, $u];
            $sum += $this->range($this->pos[$this->head[$u]], $this->pos[$u]);   // whole stretch of the chain
            $blocks++;
            $u = $this->parent[$this->head[$u]];                                  // hop to the next chain
        }
        if ($this->depth[$u] > $this->depth[$v]) [$u, $v] = [$v, $u];
        $sum += $this->range($this->pos[$u], $this->pos[$v]);
        return [$sum, $blocks + 1];
    }
}

$edges = [[1, 2], [1, 3], [2, 4], [2, 5], [4, 6], [4, 7], [3, 8], [8, 9]];
$cups  = [0, 3, 1, 4, 1, 5, 9, 2, 6, 5];              // cups[stall], index 0 unused
$t = new HLD(9, $edges, $cups);
[$sum, $blocks] = $t->pathSum(7, 9);
echo "Path 7..9 total = $sum using $blocks blocks\n";   // 22 using 3 blocks

JavaScript

// Heavy-Light Decomposition with path sums (static values, prefix sums over chains).
class HLD {
  constructor(n, edges, val) {                    // nodes are 1..n
    this.adj = Array.from({ length: n + 1 }, () => []);
    for (const [a, b] of edges) { this.adj[a].push(b); this.adj[b].push(a); }
    const z = () => new Array(n + 1).fill(0);
    this.parent = z(); this.depth = z(); this.size = z();
    this.heavy = z(); this.head = z(); this.pos = z();
    this.cur = 0;
    this.dfs1(1, 0);
    this.dfs2(1, 1);
    const line = new Array(n).fill(0);
    for (let v = 1; v <= n; v++) line[this.pos[v]] = val[v];   // values in chain order
    this.prefix = [0];
    for (const x of line) this.prefix.push(this.prefix[this.prefix.length - 1] + x);
  }

  dfs1(u, p) {
    this.size[u] = 1;
    for (const v of this.adj[u]) {
      if (v === p) continue;
      this.parent[v] = u;
      this.depth[v] = this.depth[u] + 1;
      this.dfs1(v, u);
      this.size[u] += this.size[v];
      if (this.heavy[u] === 0 || this.size[v] > this.size[this.heavy[u]]) this.heavy[u] = v;
    }
  }

  dfs2(u, h) {
    this.head[u] = h;
    this.pos[u] = this.cur++;
    if (this.heavy[u]) this.dfs2(this.heavy[u], h);            // heavy child continues the chain
    for (const v of this.adj[u]) {
      if (v !== this.parent[u] && v !== this.heavy[u]) this.dfs2(v, v);   // light child starts a new chain
    }
  }

  range(l, r) { return this.prefix[r + 1] - this.prefix[l]; }

  // Sum of values on the path u..v, plus how many chain blocks were used.
  pathSum(u, v) {
    let sum = 0, blocks = 0;
    while (this.head[u] !== this.head[v]) {
      if (this.depth[this.head[u]] < this.depth[this.head[v]]) [u, v] = [v, u];
      sum += this.range(this.pos[this.head[u]], this.pos[u]);  // whole stretch of the chain
      blocks++;
      u = this.parent[this.head[u]];                            // hop to the next chain
    }
    if (this.depth[u] > this.depth[v]) [u, v] = [v, u];
    sum += this.range(this.pos[u], this.pos[v]);
    return [sum, blocks + 1];
  }
}

const edges = [[1, 2], [1, 3], [2, 4], [2, 5], [4, 6], [4, 7], [3, 8], [8, 9]];
const cups = [0, 3, 1, 4, 1, 5, 9, 2, 6, 5];            // cups[stall], index 0 unused
const t = new HLD(9, edges, cups);
const [sum, blocks] = t.pathSum(7, 9);
console.log('Path 7..9 total = ' + sum + ' using ' + blocks + ' blocks');   // 22 using 3 blocks

Java

import java.util.*;

public class Main {
    // Heavy-Light Decomposition with path sums (static values, prefix sums over chains).
    static class HLD {
        int[] parent, depth, size, heavy, head, pos;
        long[] prefix;
        List<List<Integer>> adj = new ArrayList<>();
        int cur = 0;

        HLD(int n, int[][] edges, int[] val) {                  // nodes are 1..n
            for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());
            for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); }
            parent = new int[n + 1]; depth = new int[n + 1]; size = new int[n + 1];
            heavy = new int[n + 1]; head = new int[n + 1]; pos = new int[n + 1];
            dfs1(1, 0);
            dfs2(1, 1);
            int[] line = new int[n];
            for (int v = 1; v <= n; v++) line[pos[v]] = val[v];  // values in chain order
            prefix = new long[n + 1];
            for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + line[i];
        }

        void dfs1(int u, int p) {
            size[u] = 1;
            for (int v : adj.get(u)) {
                if (v == p) continue;
                parent[v] = u;
                depth[v] = depth[u] + 1;
                dfs1(v, u);
                size[u] += size[v];
                if (heavy[u] == 0 || size[v] > size[heavy[u]]) heavy[u] = v;
            }
        }

        void dfs2(int u, int h) {
            head[u] = h;
            pos[u] = cur++;
            if (heavy[u] != 0) dfs2(heavy[u], h);                // heavy child continues the chain
            for (int v : adj.get(u)) {
                if (v != parent[u] && v != heavy[u]) dfs2(v, v); // light child starts a new chain
            }
        }

        long range(int l, int r) { return prefix[r + 1] - prefix[l]; }

        // Sum of values on the path u..v, plus how many chain blocks were used.
        long[] pathSum(int u, int v) {
            long sum = 0;
            int blocks = 0;
            while (head[u] != head[v]) {
                if (depth[head[u]] < depth[head[v]]) { int t = u; u = v; v = t; }
                sum += range(pos[head[u]], pos[u]);              // whole stretch of the chain
                blocks++;
                u = parent[head[u]];                             // hop to the next chain
            }
            if (depth[u] > depth[v]) { int t = u; u = v; v = t; }
            sum += range(pos[u], pos[v]);
            return new long[]{sum, blocks + 1};
        }
    }

    public static void main(String[] args) {
        int[][] edges = {{1, 2}, {1, 3}, {2, 4}, {2, 5}, {4, 6}, {4, 7}, {3, 8}, {8, 9}};
        int[] cups = {0, 3, 1, 4, 1, 5, 9, 2, 6, 5};             // cups[stall], index 0 unused
        HLD t = new HLD(9, edges, cups);
        long[] res = t.pathSum(7, 9);
        System.out.println("Path 7..9 total = " + res[0] + " using " + res[1] + " blocks");   // 22 using 3 blocks
    }
}

Go

package main

import "fmt"

// HLD: Heavy-Light Decomposition with path sums (static values, prefix sums over chains).
type HLD struct {
	parent, depth, size, heavy, head, pos []int
	prefix                                []int
	adj                                   [][]int
	cur                                   int
}

func NewHLD(n int, edges [][2]int, val []int) *HLD { // nodes are 1..n
	t := &HLD{
		parent: make([]int, n+1), depth: make([]int, n+1), size: make([]int, n+1),
		heavy: make([]int, n+1), head: make([]int, n+1), pos: make([]int, n+1),
		adj: make([][]int, n+1),
	}
	for _, e := range edges {
		t.adj[e[0]] = append(t.adj[e[0]], e[1])
		t.adj[e[1]] = append(t.adj[e[1]], e[0])
	}
	t.dfs1(1, 0)
	t.dfs2(1, 1)
	line := make([]int, n)
	for v := 1; v <= n; v++ {
		line[t.pos[v]] = val[v] // values in chain order
	}
	t.prefix = []int{0}
	for _, x := range line {
		t.prefix = append(t.prefix, t.prefix[len(t.prefix)-1]+x)
	}
	return t
}

func (t *HLD) dfs1(u, p int) {
	t.size[u] = 1
	for _, v := range t.adj[u] {
		if v == p {
			continue
		}
		t.parent[v] = u
		t.depth[v] = t.depth[u] + 1
		t.dfs1(v, u)
		t.size[u] += t.size[v]
		if t.heavy[u] == 0 || t.size[v] > t.size[t.heavy[u]] {
			t.heavy[u] = v
		}
	}
}

func (t *HLD) dfs2(u, h int) {
	t.head[u] = h
	t.pos[u] = t.cur
	t.cur++
	if t.heavy[u] != 0 {
		t.dfs2(t.heavy[u], h) // heavy child continues the chain
	}
	for _, v := range t.adj[u] {
		if v != t.parent[u] && v != t.heavy[u] {
			t.dfs2(v, v) // light child starts a new chain
		}
	}
}

func (t *HLD) rangeSum(l, r int) int { return t.prefix[r+1] - t.prefix[l] }

// PathSum returns the sum of values on the path u..v, plus how many chain blocks were used.
func (t *HLD) PathSum(u, v int) (int, int) {
	sum, blocks := 0, 0
	for t.head[u] != t.head[v] {
		if t.depth[t.head[u]] < t.depth[t.head[v]] {
			u, v = v, u
		}
		sum += t.rangeSum(t.pos[t.head[u]], t.pos[u]) // whole stretch of the chain
		blocks++
		u = t.parent[t.head[u]] // hop to the next chain
	}
	if t.depth[u] > t.depth[v] {
		u, v = v, u
	}
	sum += t.rangeSum(t.pos[u], t.pos[v])
	return sum, blocks + 1
}

func main() {
	edges := [][2]int{{1, 2}, {1, 3}, {2, 4}, {2, 5}, {4, 6}, {4, 7}, {3, 8}, {8, 9}}
	cups := []int{0, 3, 1, 4, 1, 5, 9, 2, 6, 5} // cups[stall], index 0 unused
	t := NewHLD(9, edges, cups)
	sum, blocks := t.PathSum(7, 9)
	fmt.Printf("Path 7..9 total = %d using %d blocks\n", sum, blocks) // 22 using 3 blocks
}

Time: O(n) to build, O(log n) chain hops per path query · Extra space: O(n). With a segment tree over the chain order, updates and path queries cost O(log² n).

Watch out for

  • Choosing the heavy child by depth instead of by subtree size. Size is what guarantees few chain hops.
  • Numbering nodes in plain DFS order so a chain is not consecutive. Visit the heavy child first.
  • Forgetting the final stretch inside the last shared chain after the loop ends.

Quick check

  1. Which child becomes the heavy child?
    • The child with the largest subtree
    • The first child
    • The deepest leaf
  2. Why must heavy chains be numbered consecutively?
    • To make output prettier
    • So a chain becomes a plain range for prefix sums or a segment tree
    • DFS needs it
  3. How many chains does any root-to-node path touch?
    • About n
    • Exactly one
    • About log n