Advanced 12 min

Segment trees and range queries

A segment tree stores summaries for ranges so a query can combine only the pieces it needs.

How it works

During a query, a node can be outside the range, completely inside it, or partly inside it. Return the neutral result, the stored summary, or the combination of both children respectively. During a point update, move from the affected leaf back to the root and recompute those summaries.

Walk through an example

For [2, 4, 1, 8], the left child can hold the sum for [2, 4] and the right child the sum for [1, 8]. The root combines both.

What to watch for

Define a neutral value for nonoverlapping segments. For sums that is zero, while for a range minimum it has to act like positive infinity.

Code example

# Leaves start at index size, with index zero unused.
def set_value(tree, size, index, value):
    node = size + index
    tree[node] = value
    while node > 1:
        node //= 2
        tree[node] = tree[2 * node] + tree[2 * node + 1]

Check your understanding

What is the new sum at the root?

See the example and explanation
Worked example
Given [2, 4, 1, 8]. Change index 1 from 4 to 7.
Answer 18

The left child changes from 6 to 9. The right child stays 9. The root combines them to get 18.

Open practice problem
Next lessonMonotonic stacks