Skip to content
StackDecode
Advanced data structuresAnimated

Segment Tree

A tree where each node stores a summary of a range.

Time

O(log n) query/update

Extra space

O(n)

Use it for

Range sums/minimums with updates.

How it works

  1. A segment tree stores the sum of a range in every node: the root covers everything, each child covers half of its parent, and the leaves are single items.
  2. Build: sums are computed bottom-up, each node = left child + right child. O(n).
  3. Query a range [l, r]: start at the root. A node fully inside the range contributes its stored sum at once. A node completely outside contributes nothing. A node that only overlaps is split into its two children.
  4. At most about 2 log n nodes are partly overlapped, so a query is O(log n) rather than O(n). (Change "sum" to min, max or gcd and the same tree works.)

Watch it run

Loading animation…