AlgoViz

Segment tree

hard 24 min

A segment tree is a binary tree in which every node stores the answer (sum, min, max, GCD) for one range of an array.

Video lesson · Chapter 1 of 8

Room occupancy board

0:00 / 6:08

Segment trees in 75 seconds

1:22Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Split ranges in half. The root owns the whole array; each node's range is cut at mid until every leaf holds one element

Understand it

Start here

What a segment tree is

  • Recap: binary trees

    Every node has at most two children and a complete tree has about log⁡2n\log_2 n levels. See binary trees.

  • Recap: recursion

    Build, query and update are all recursive: a base case at the leaf and a combine step on the way back. See recursion.

  • Recap: prefix sums

    O(1)O(1) range sums on a fixed array, but one change costs O(n)O(n). See prefix sums.

A segment tree is a binary tree built over an array. Each node stores the answer for one contiguous range (segment) of the array: the root covers everything, its children cover the two halves, and each leaf covers a single element. It answers range queries such as sum, min, max or GCD and applies point updates, both in O(log⁡n)O(\log n).

  • Range queries

    Sum, min, max or GCD of any a[l..r]a[l..r] in O(log⁡n)O(\log n).

  • Point updates

    Change any element and fix the stored answers in O(log⁡n)O(\log n).

  • Both fast at once

    Prefix sums or a plain array make one operation fast and the other O(n)O(n). This makes both logarithmic.

Motivation

Why not a loop or prefix sums?

Take a=[1,3,5,7,9,11,13,15]a = [1, 3, 5, 7, 9, 11, 13, 15] and a stream of two kinds of request: sum of $a[l..r]$ and set $a[i] = v$. Each familiar tool is fast at one and slow at the other.

ApproachRange queryPoint updateGood for
Plain loop over the arrayO(n)O(n)O(1)O(1)Rare queries, small arrays
Prefix sums: P[r+1]−P[l]P[r+1] - P[l]O(1)O(1)O(n)O(n) to fix PPStatic data, no updates
Segment treeO(log⁡n)O(\log n)O(log⁡n)O(\log n)Queries and updates mixed

Cost of n queries plus n updates

n⋅O(log⁡n)+n⋅O(log⁡n)⏟segment tree=O(nlog⁡n)vsn⋅O(n)⏟loop or prefix sums=O(n2)\underbrace{n \cdot O(\log n) + n \cdot O(\log n)}_{\text{segment tree}} = O(n \log n) \qquad \text{vs} \qquad \underbrace{n \cdot O(n)}_{\text{loop or prefix sums}} = O(n^2)
At n=105n = 10^5 that is roughly 3.4×1063.4 \times 10^6 steps against 101010^{10}. For a static array, prefix sums are still better; for rare queries, the plain loop is simpler.

Anatomy

Every node owns a range

A node stores three things: its value (the merged answer) and the left and right ends of its range. In the usual array layout the range is not stored at all; it is passed down the recursion as lo and hi.

Sum tree over [1, 3, 5, 7, 9, 11, 13, 15]

Each parent is the sum of its children, and every level adds up to 64. Leaves under nodes 6 and 7 (9, 11, 13, 15) are left out to keep the picture readable.

Array layout (root at index 1)

For node at index iIndexRange
Root1[0,n−1][0, n - 1]
Left child2 * i[lo,mid][lo, mid] with mid=⌊(lo+hi)/2⌋mid = \lfloor (lo + hi)/2 \rfloor
Right child2 * i + 1[mid+1,hi][mid + 1, hi]
Parenti // 2the range that contains this one
The same index arithmetic as a binary heap, shifted to start at 1 so the children are simply 2i2i and 2i+12i + 1.

Operation 1

Building it bottom-up

build(node, lo, hi)

A post-order walk: both children are finished before the parent is computed.

Build is linear

T(n)=2 T ⁣(n2)+O(1)  ⇒  T(n)=O(n),nodes=n+n2+n4+⋯+1=2n−1T(n) = 2\,T\!\left(\tfrac{n}{2}\right) + O(1) \;\Rightarrow\; T(n) = O(n), \qquad \text{nodes} = n + \tfrac{n}{2} + \tfrac{n}{4} + \dots + 1 = 2n - 1
Each of the 2n−12n - 1 nodes is computed once from two children, so building costs O(n)O(n), the same as building prefix sums.
Python
class SegmentTree:    def __init__(self, a):        self.n = len(a)        self.tree = [0] * (4 * self.n)        self._build(a, 1, 0, self.n - 1)    def _build(self, a, node, lo, hi):        if lo == hi:            self.tree[node] = a[lo]            return        mid = (lo + hi) // 2        self._build(a, 2 * node, lo, mid)        self._build(a, 2 * node + 1, mid + 1, hi)        self.tree[node] = self.tree[2 * node] + self.tree[2 * node + 1]    def query(self, l, r, node=1, lo=0, hi=None):        if hi is None:            hi = self.n - 1        if r < lo or hi < l:            # no overlap            return 0        if l <= lo and hi <= r:         # full overlap            return self.tree[node]        mid = (lo + hi) // 2            # partial overlap        return (self.query(l, r, 2 * node, lo, mid)                + self.query(l, r, 2 * node + 1, mid + 1, hi))    def update(self, i, val, node=1, lo=0, hi=None):        if hi is None:            hi = self.n - 1        if lo == hi:            self.tree[node] = val            return        mid = (lo + hi) // 2        if i <= mid:            self.update(i, val, 2 * node, lo, mid)        else:            self.update(i, val, 2 * node + 1, mid + 1, hi)        self.tree[node] = self.tree[2 * node] + self.tree[2 * node + 1]st = SegmentTree([1, 3, 5, 7, 9, 11, 13, 15])print(st.tree[1])        # 64print(st.query(1, 4))    # 24st.update(2, 10)         # a[2]: 5 -> 10print(st.query(1, 4))    # 29print(st.tree[1])        # 69
A complete sum segment tree: build, query and update.
Edit and run it in your browser

Operation 2

Range query: three cases

To answer sum(1, 4) =3+5+7+9=24= 3 + 5 + 7 + 9 = 24, start at the root and compare each node's range [lo,hi][lo, hi] with the query [l,r][l, r]. Exactly one of three cases applies.

  • No overlap

    r<lor < lo or hi<lhi < l. The node is useless: return the identity (0 for sum).

  • Full overlap

    l≤lol \le lo and hi≤rhi \le r. Return the stored value and do not go deeper.

  • Partial overlap

    Anything else. Ask both children and merge their answers.

query(node, lo, hi, l, r)

On [1, 3, 5, 7, 9, 11, 13, 15] the answer comes from three stored values: [1] = 3, [2-3] = 12 and [4] = 9. Eleven of the 15 nodes are visited.

Proof

Why a query is O(log n)

Look at one level of the tree. Its nodes are disjoint ranges side by side. A node can only be partial if the query's left edge ll or right edge rr falls strictly inside it, and each edge falls inside at most one node per level.

At most 2 nodes split per level

#{partial nodes on a level}≤2  ⇒  #{visited nodes on the next level}≤2×2=4\#\{\text{partial nodes on a level}\} \le 2 \;\Rightarrow\; \#\{\text{visited nodes on the next level}\} \le 2 \times 2 = 4
Every visited node is a child of a partial node, so no level sees more than 4 visits. Full and no-overlap nodes stop immediately.

Total work

visits  ≤  4⋅(⌈log⁡2n⌉+1)=O(log⁡n)\text{visits} \;\le\; 4 \cdot \left(\lceil \log_2 n \rceil + 1\right) = O(\log n)
Measured on a near-full range [1,n−2][1, n - 2]: 11 visits at n=8n = 8, 39 at n=1024n = 1024 and 77 at n=106n = 10^6. A loop would read a million values.

Operation 3

Point update: one path up

Setting a[2]=10a[2] = 10 (it was 5) only invalidates the nodes whose range contains index 2: [2][2], [2,3][2,3], [0,3][0,3] and [0,7][0,7]. Walk down to the leaf, change it, and recompute each ancestor on the way back: 5→105 \to 10, 12→1712 \to 17, 16→2116 \to 21, 64→6964 \to 69.

update(node, lo, hi, i, val)

Only one child is visited per level, and every parent on the path is recomputed after its child changes.
a[2] = 10, bottom to top
  1. 1[2]5 → 10
  2. 2[2-3]10 + 7 = 17
  3. 3[0-3]4 + 17 = 21
  4. 4[0-7]21 + 48 = 69

Siblings such as [0-1] and [4-7] are read but never rewritten.

Update cost is the height

nodes changed=h+1=⌈log⁡2n⌉+1=O(log⁡n)(n=8:  3+1=4)\text{nodes changed} = h + 1 = \lceil \log_2 n \rceil + 1 = O(\log n) \qquad (n = 8:\; 3 + 1 = 4)
Compare prefix sums, where changing a[i]a[i] forces every P[j]P[j] with j>ij > i to change: O(n)O(n).

Space

Why the array has 4n slots

With the root at 1 and children at 2i2i and 2i+12i + 1, a tree of height hh can use indexes up to 2h+1−12^{h+1} - 1. When nn is not a power of two, some branches are deeper than others and leave gaps, so 2n2n slots are not enough.

The 4n bound

h=⌈log⁡2n⌉  ⇒  2h<2n  ⇒  max index≤2h+1−1<4nh = \lceil \log_2 n \rceil \;\Rightarrow\; 2^{h} < 2n \;\Rightarrow\; \text{max index} \le 2^{h+1} - 1 < 4n
Since 2h−1<n2^{h-1} < n, we get 2h<2n2^h < 2n and the largest index is below 2⋅2n=4n2 \cdot 2n = 4n. Space is O(n)O(n); the 4 is a safe constant.
nLargest index used2n4n2n enough?
591020yes
6131224no
8151632yes
100253200400no
Powers of two fit in 2n2n exactly; n=6n = 6 (the original example array) already overflows it.

Variants

Sum, min, max, GCD: change the merge

QueryParent valueNo-overlap identityOn [5, 2, 8, 6, 1, 9, 4, 7], range [2, 6]
Range sum (RSQ)left + right008+6+1+9+4=288 + 6 + 1 + 9 + 4 = 28
Range min (RMQ)min(left, right)+∞+\infty11
Range maxmax(left, right)−∞-\infty99
Range GCDgcd(left, right)00 (since gcd⁡(0,x)=x\gcd(0, x) = x)gcd⁡(8,6,1,9,4)=1\gcd(8, 6, 1, 9, 4) = 1
The tree shape and the three query cases never change. Only the merge and its identity do, and they must change together.

What makes a merge work

f(f(x,y),z)=f(x,f(y,z))f(e,x)=f(x,e)=xf(f(x, y), z) = f(x, f(y, z)) \qquad f(e, x) = f(x, e) = x
The merge ff must be associative so pieces can be combined in any grouping, and it needs an identity ee for the no-overlap case. Sum, min, max, GCD, XOR and matrix product all qualify.
Python
import mathclass SegTree:    def __init__(self, a, merge, identity):        self.n, self.f, self.e = len(a), merge, identity        self.t = [identity] * (4 * self.n)        self._build(a, 1, 0, self.n - 1)    def _build(self, a, k, lo, hi):        if lo == hi:            self.t[k] = a[lo]            return        mid = (lo + hi) // 2        self._build(a, 2 * k, lo, mid)        self._build(a, 2 * k + 1, mid + 1, hi)        self.t[k] = self.f(self.t[2 * k], self.t[2 * k + 1])    def query(self, l, r, k=1, lo=0, hi=None):        hi = self.n - 1 if hi is None else hi        if r < lo or hi < l:            return self.e        if l <= lo and hi <= r:            return self.t[k]        mid = (lo + hi) // 2        return self.f(self.query(l, r, 2 * k, lo, mid),                      self.query(l, r, 2 * k + 1, mid + 1, hi))a = [5, 2, 8, 6, 1, 9, 4, 7]print(SegTree(a, lambda x, y: x + y, 0).query(2, 6))         # 28print(SegTree(a, min, float("inf")).query(2, 6))             # 1print(SegTree(a, max, float("-inf")).query(2, 6))            # 9print(SegTree(a, math.gcd, 0).query(2, 3))                   # gcd(8, 6) = 2
One class, any associative merge: pass the function and its identity.
Edit and run it in your browser

Choosing

Segment tree vs prefix sums vs Fenwick tree

Prefix sumsFenwick tree (BIT)Segment tree
BuildO(n)O(n)O(n)O(n)O(n)O(n)
Range queryO(1)O(1)O(log⁡n)O(\log n)O(log⁡n)O(\log n)
Point updateO(n)O(n)O(log⁡n)O(\log n)O(log⁡n)O(\log n)
Range min / maxnonot with updates in generalyes
Range updatedifference array, offlinewith two trees, sums onlyyes, lazy propagation
Space and coden+1n + 1 slots, 3 linesn+1n + 1 slots, about 10 lines4n4n slots, about 30 lines
A Fenwick tree is smaller and faster in practice for sums because it relies on subtraction (sum(l,r)=pre(r)−pre(l−1)\text{sum}(l, r) = \text{pre}(r) - \text{pre}(l - 1)). Min and max cannot be subtracted, which is where the segment tree takes over.

Which structure?

For tiny arrays (a few hundred elements) or very few queries, a plain loop is the simplest correct answer.

Use a segment tree when

  • Range queries (sum, min, max, GCD) and point updates are both frequent.
  • The merge is not invertible, so prefix tricks fail (min, max, GCD).
  • Whole ranges are updated at once (with lazy propagation).
  • A competitive programming problem has 10510^5 operations on 10510^5 elements.

Use something simpler when

  • Nothing ever changes: prefix sums, or a sparse table for min and max.
  • Only sums with point updates: a Fenwick tree is shorter.
  • The array is small: a loop is fast enough and hard to get wrong.
  • You only read single elements: direct array access.

Range updates

Lazy propagation

Now suppose the request is add $v$ to every element of $a[l..r]$. Doing r−l+1r - l + 1 point updates costs O(nlog⁡n)O(n \log n). Lazy propagation applies the change to the same O(log⁡n)O(\log n) fully covered nodes a query would use, and leaves a note (a lazy tag) saying "my children still owe +v+v". The note is pushed down only when someone later needs to go below that node.

range_add(node, lo, hi, l, r, v)

Queries call the same push_down before splitting a partial node, so a pending tag is always applied before anyone reads below it.

Applying a pending add to a whole range

sum[lo..hi]+=v⋅(hi−lo+1)⇒range update and range query both O(log⁡n)\text{sum}[lo..hi] \mathrel{+}= v \cdot (hi - lo + 1) \qquad \Rightarrow \qquad \text{range update and range query both } O(\log n)
A sum node can absorb the update without touching its leaves because the effect on the sum is known: vv times the range length. For a min or max node with range add, the stored value simply increases by vv.
Python
class LazySegTree:    def __init__(self, n):        self.n = n        self.t = [0] * (4 * n)      # sums        self.lz = [0] * (4 * n)     # pending add for the children    def _apply(self, k, lo, hi, v):        self.t[k] += v * (hi - lo + 1)        self.lz[k] += v    def _push(self, k, lo, hi):        if self.lz[k]:            mid = (lo + hi) // 2            self._apply(2 * k, lo, mid, self.lz[k])            self._apply(2 * k + 1, mid + 1, hi, self.lz[k])            self.lz[k] = 0    def add(self, l, r, v, k=1, lo=0, hi=None):        hi = self.n - 1 if hi is None else hi        if r < lo or hi < l:            return        if l <= lo and hi <= r:            self._apply(k, lo, hi, v)            return        self._push(k, lo, hi)        mid = (lo + hi) // 2        self.add(l, r, v, 2 * k, lo, mid)        self.add(l, r, v, 2 * k + 1, mid + 1, hi)        self.t[k] = self.t[2 * k] + self.t[2 * k + 1]    def total(self, l, r, k=1, lo=0, hi=None):        hi = self.n - 1 if hi is None else hi        if r < lo or hi < l:            return 0        if l <= lo and hi <= r:            return self.t[k]        self._push(k, lo, hi)        mid = (lo + hi) // 2        return self.total(l, r, 2 * k, lo, mid) + self.total(l, r, 2 * k + 1, mid + 1, hi)s = LazySegTree(8)s.add(2, 5, 3)         # a = [0, 0, 3, 3, 3, 3, 0, 0]s.add(4, 7, 1)         # a = [0, 0, 3, 3, 4, 4, 1, 1]print(s.total(0, 7))   # 16print(s.total(3, 4))   # 7
Range add and range sum with lazy tags.
Edit and run it in your browser

Recap

Key takeaways

Key points

  • Each node stores the merged answer for one range; children split it at mid=⌊(lo+hi)/2⌋mid = \lfloor (lo + hi)/2 \rfloor; leaves are single elements.
  • Root at index 1, children at 2i2i and 2i+12i + 1; allocate 4n4n slots for the recursive layout.
  • Build is O(n)O(n); range query and point update are O(log⁡n)O(\log n) because at most 4 nodes per level are visited and an update walks one path.
  • Query cases: no overlap returns the identity, full overlap returns the node, partial overlap recurses into both children.
  • Sum, min, max and GCD differ only in the merge and its identity (0, +∞+\infty, −∞-\infty, 0).
  • Static data: prefix sums. Sums with updates: Fenwick tree or segment tree. Min or max with updates, or range updates: segment tree (with lazy propagation).

Sources