Skip to the content.

12. Segment Tree (Range Sum Queries)

Back to the index

A binary tree where each node stores an aggregate (sum, min, max) of an index range. Range queries and point updates are O(log n), and the aggregate can be anything associative.

How it works

The root covers the whole array, and each node splits its range in half between two children. Leaves are single items. Each node stores the sum of its range.

To query [left, right], start at the root. A node whose range is fully inside the query contributes its stored sum and stops. A node with no overlap contributes 0 and stops. A partial overlap asks both children. At most about four nodes per level are visited, so a query is O(log n). An update changes one leaf and recomputes the sums on its path back to the root.

Swap + for min or max (and 0 for infinity) to answer range-minimum or range-maximum queries.

Diagram

graph TD
    s1["range 0 to 5: sum 21"]
    s2["range 0 to 2: sum 8"]
    s4["range 0 to 1: sum 3"]
    s8["range 0 to 0: sum 2"]
    s9["range 1 to 1: sum 1"]
    s4 --> s8
    s4 --> s9
    s5["range 2 to 2: sum 5"]
    s2 --> s4
    s2 --> s5
    s3["range 3 to 5: sum 13"]
    s6["range 3 to 4: sum 7"]
    s12["range 3 to 3: sum 3"]
    s13["range 4 to 4: sum 4"]
    s6 --> s12
    s6 --> s13
    s7["range 5 to 5: sum 6"]
    s3 --> s6
    s3 --> s7
    s1 --> s2
    s1 --> s3

Step-by-step trace

Input: Array [2, 1, 5, 3, 4, 6] (indices 0 to 5). Query the sum of indices 1 to 4.

Visit Node range Node sum Case Contributes
1 0..5 21 partial, split -
2 0..2 8 partial, split -
3 0..1 3 partial, split -
4 0..0 2 no overlap 0
5 1..1 1 fully inside 1
6 2..2 5 fully inside 5
7 3..5 13 partial, split -
8 3..4 7 fully inside 7
9 5..5 6 no overlap 0

Result: Sum = 13 (1 + 5 + 3 + 4). Fully covered nodes were used whole instead of visiting their leaves.

Complexity

Operation Time Space
Range query O(log n) O(log n) recursion
Point update O(log n) O(log n) recursion
Build O(n) O(n), allocate 4n slots

Python reference implementation

class SegmentTree:
    """Range-sum segment tree with point updates (recursive, 1-indexed nodes)."""

    def __init__(self, values):
        self.n = len(values)
        self.sums = [0] * (4 * max(1, self.n))
        if self.n:
            self._build(values, 1, 0, self.n - 1)

    def _build(self, values, node, lo, hi):
        if lo == hi:
            self.sums[node] = values[lo]
            return
        mid = (lo + hi) // 2
        self._build(values, 2 * node, lo, mid)
        self._build(values, 2 * node + 1, mid + 1, hi)
        self.sums[node] = self.sums[2 * node] + self.sums[2 * node + 1]

    def update(self, index, value, node=1, lo=0, hi=None):
        hi = self.n - 1 if hi is None else hi
        if lo == hi:
            self.sums[node] = value
            return
        mid = (lo + hi) // 2
        if index <= mid:
            self.update(index, value, 2 * node, lo, mid)
        else:
            self.update(index, value, 2 * node + 1, mid + 1, hi)
        self.sums[node] = self.sums[2 * node] + self.sums[2 * node + 1]

    def query(self, left, right, node=1, lo=0, hi=None):
        """Sum of values[left..right], inclusive."""
        hi = self.n - 1 if hi is None else hi
        if right < lo or hi < left:
            return 0                                  # no overlap
        if left <= lo and hi <= right:
            return self.sums[node]                    # full cover
        mid = (lo + hi) // 2                          # partial: ask both children
        return (self.query(left, right, 2 * node, lo, mid) +
                self.query(left, right, 2 * node + 1, mid + 1, hi))

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Fenwick Tree (Binary Indexed Tree) Next: Graphs: Breadth-First Search (BFS)