Segment trees: build, query and update

Video lessonComing soon

1 Totals that keep changing

Eight salespeople sit in a row, numbered 0 to 7. This week they closed these orders:

4011822374653697
Orders closed by salespeople 0 to 7

Two kinds of request keep coming. One asks for the total of a range, such as salespeople 2 to 6. The other changes one number. A problem can send 10⁵ of each over 10⁵ values, and the easy ways fail:

  • A loop per question. Each question adds up to 10⁵ values.
  • Prefix sums. Each question is one subtraction, but a change at index 0 shifts every prefix after it.

Either way, that is around 10¹⁰ steps, far past the time limit, so it gets Time Limit Exceeded (TLE). The Fenwick tree lesson fixed this for sums. A minimum cannot be written as one prefix minus another, so it needs something else.

A company handles this with its org chart. Every boss has two reports and knows the total of their whole team. To answer "2 to 6", the CEO adds the totals of a few bosses whose teams fit inside the range. When one number changes, only the bosses above that person fix their totals.

2 A tree of ranges

That org chart is a segment tree. Each node covers a range of indexes:

  • The root covers the whole array, 0 to n − 1.
  • A node covering start to end splits at mid = (start + end) / 2, rounded down. The left child covers start to mid, and the right child covers mid + 1 to end.
  • The splitting stops at a single index. That node is a leaf, and it holds one value.

Every other node holds the total of its range, which is the sum of its two children's totals:

00-110-322-330-744-554-766-77
The range each node covers
451158102407136253129
The total each node holds

The node for 0-1 holds 4 + 1 = 5, and the root holds 15 + 25 = 40.

To build the tree, a recursive function fills a node's two children first, then adds their totals. Each boss waits for two answers from below, as in the tree basics lesson. n values make 2n − 1 nodes: n leaves, and n − 1 bosses, because each boss joins two teams into one. Each node is filled once, so the build is O(n).

3 A query: three cases

A query asks for the total from l to r. It starts at the root, and each node it visits compares its own range with [l, r]:

  • No overlap. The node's range lies fully outside [l, r]. It returns 0, which adds nothing.
  • Full overlap. The range lies fully inside [l, r]. It returns its total at once and does not look further down.
  • Partial overlap. Part is inside and part is outside. It asks both children and returns the sum of their answers.

Here is the query for 2 to 6. The array shows the values taken so far, and the faded ones were ruled out:

Query 2 to 6
451158102407136253129
Nodes visited
4011822374653697
0-7 is partly inside: ask both halves

The recursion visits the nodes in this order:

Node coversAgainst 2-6Returns
0-7partial10 + 16 = 26
0-3partial0 + 10 = 10
0-1none0
2-3full10
4-7partial13 + 3 = 16
4-5full13
6-7partial3 + 0 = 3
6full3
7none0

The answer came from three stored totals, 10, 13 and 3. Nodes 0-1 and 7 were visited only to find that they lie outside, and nothing below a full or a no-overlap node was visited at all.

4 A point update

Salesperson 3 closes more orders, and their number changes from 2 to 11. Only the nodes whose range holds index 3 have a wrong total now: 3, 2-3, 0-3 and 0-7. Every other total is still right.

An update walks from the root down to the leaf for index i. At each node it goes left when i ≤ mid, and right otherwise. It sets the leaf. Then, on the way back up, each node on the path adds its two children again:

Set index 3 to 11
451158102407136253129
Walk down: 0-7, 0-3, 2-3, then 3

The update touched one node per level. Now the query for 2 to 6 reads 19 + 13 + 3 = 35.

5 Why a query visits so few nodes

On 8 values, the query visited 9 of the 15 nodes. That looks like a lot, but the count grows with the number of levels, not with n.

A query makes two cuts in the array: one just before l and one just after r. A node overlaps partly only when a cut passes through its range. On one level, the ranges sit side by side without overlapping, so each cut passes through at most one of them. That leaves at most two partial nodes per level. Only they ask their children, so at most four nodes are visited on any level.

In our query, the left cut ran through 0-3 and the right cut through 4-7. On the next level, only 6-7 was cut.

A tree over 10⁵ values has about 17 levels, so a query visits at most about 70 nodes.

OperationTimeWhy
BuildO(n)each of the 2n − 1 nodes is filled once
QueryO(log n)at most four nodes per level
UpdateO(log n)one node per level, down and back up
MemoryO(n)an array of 4n, in the next section

With 10⁵ queries and updates, that is around 10⁷ steps instead of 10¹⁰.

6 One array, and the code

A segment tree needs no node objects. Like the heap in the tree basics lesson, it lives in one array, tree. The root is at index 1, and the node at index i has its children at 2i and 2i + 1. Index 0 stays empty:

0401152253541051361274819810211712613314915
tree[3] covers 4-7. Its children are at 6 and 7

A node does not store its range. Each function gets it as start and end, and works out the children's ranges from mid.

When n is not a power of two, the tree is lopsided, and the array gets gaps:

00-110-220-533-443-55
6 values: index 13 is used, but 10 and 11 are empty

So 2n places are not always enough. Here 2n is 12, and the tree needs index 13. 4n is always enough: the tree is at most log₂ n levels deep, rounded up, and a full tree that deep has fewer than 4n places.

update and query start the recursion at the root, node 1, which covers 0 to n − 1.

C++

Totals in long long. 10⁵ values of 10⁹ add up to 10¹⁴, and an int holds only about 2 × 10⁹.

Totals in long. 10⁵ values of 10⁹ add up to 10¹⁴, and an int holds only about 2 × 10⁹.

Nothing to watch. Python's integers grow as needed, so a total of 10¹⁴ is fine.

Nothing to watch. Numbers stay exact up to about 9 × 10¹⁵, so a total of 10¹⁴ is safe.

int is 64 bits on today's machines, so a total of 10¹⁴ fits.

Totals in i64. Each value is converted with as i64 when it goes into the tree. An i32 sum past 2 × 10⁹ overflows.

Totals in long. 10⁵ values of 10⁹ add up to 10¹⁴, and an int holds only about 2 × 10⁹.

7 Mistakes

  • An array of 2n. It is enough only when n is a power of two. With 6 values, the build writes to index 13 of a 12-place array and gets Runtime Error.
  • The wrong split. The halves are start to mid and mid + 1 to end. With start to mid − 1 and mid to end, node 2-3 gets mid = 2, and its right half is 2-3 again. The recursion never ends, and it gets Runtime Error.
  • Forgetting the parents. If an update sets only the leaf, the query for 2 to 6 still returns 26, not 35. It reads the old total 10 at node 2-3.
  • Returning 0 in a minimum tree. A node outside the query must return a value that never wins, and 0 can win. The minimum of 2 to 6 in our first array is 2, but node 0-1 returns 0, so the answer comes out as 0.

8 Minimum, maximum and when to use it

A minimum tree holds the smallest value of each range. Its code differs from the sum tree in two places: how two answers combine, and what a no-overlap node returns. That return value is the operation's identity, a value that changes nothing when combined with another:

OperationCombineNo overlap returns
Suma + b0
Minimummin(a, b)+∞
Maximummax(a, b)−∞
GCDgcd(a, b)0

In code, +∞ is the largest value of the type, and −∞ the smallest. The operation must also be associative. The tree grouped 2 to 6 as (8 + 2) + (7 + 6) + 3, and the grouping must not change the answer. Subtraction fails this.

The sign is an array that changes between questions about ranges:

  • The array never changes. Prefix sums or a sparse table answer faster.
  • Only sums. A Fenwick tree is shorter to write.
  • A minimum, a maximum or another combined value. Use a segment tree.

Some problems build the tree over values instead of indexes, after the coordinate compression lesson shrinks them. When one change covers a whole range, the next lesson, on lazy propagation, extends this tree.

Before coding a segment tree, write down two things: how two children's answers combine, and what a range outside the query returns.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.