Trees are everywhere in competitive programming and systems design: hierarchies, networks, parse trees. But trees resist the classic range-query tricks. A path between two nodes can zigzag unpredictably, and a naïve scan costs per query.
Heavy-Light Decomposition (HLD) — introduced in the algorithmic folklore and popularized in competitive programming — fixes this with one elegant observation: classify each edge as heavy or light.
- A heavy edge from a node to its child is the one leading to the child with the largest subtree. Every non-leaf node has exactly one heavy child.
- All other edges are light.
Chain the heavy edges together and you get a collection of heavy chains that cover the entire tree. The crucial fact: any path from a node to the root crosses at most light edges — because every time you cross a light edge upward, the subtree size at least doubles. This means any root-to-node path breaks into at most contiguous chains.
Each chain is then linearized in a DFS order so it becomes a contiguous array range. A segment tree or Fenwick tree sitting on that flat array answers any range query in . Combine the two logs and a path query or update costs total — a dramatic improvement over .
Comments
Loading comments...