Lesson 4 · Advanced structures and algorithms

Segment Trees

A segment tree is a binary tree over an array where every node stores a total for one stretch of the array. Any range is covered by O(log n) of those stretches, so both range questions and updates take O(log n).

Segment Trees concept diagramA visual explanation of the layout and operations shown in this lesson.each node stores the sum of the array range below it164121357[0..3][0..1][2..3][0][1][2][3]a range query touches only the nodes that cover it
1

When Prefix Sums Stop Working

A prefix sum array answers any range sum in O(1), as long as the array never changes. Change one element and every prefix after it is wrong, which costs O(n) to repair.

The hard case is both at once. A plain array updates in O(1) but sums a range in O(n); a prefix array does the reverse. With q operations of both kinds mixed together, either one ends up O(n × q).

A segment tree makes both O(log n). For a million elements and a million operations, that is about 20 million steps instead of up to a trillion.

The segment tree data structure is a binary tree where every node stands for an interval of the array and stores a total over it. The root covers [0, n − 1]; each node splits its interval at the middle and hands the halves to its two children; leaves cover single elements.

  • Prefix sums: O(1) query, O(n) update
  • Segment tree: O(log n) for both
  • Each node stores the total for the interval it covers
2

Building the Tree

  1. If the interval is one element, store that element (a leaf)
  2. Otherwise split at mid = (lo + hi) / 2
  3. Build the left child on [lo, mid] and the right child on [mid + 1, hi]
  4. Store the combination of the two children's values

The usual segment tree implementation builds recursively, bottom-up: a node can only be filled once both children are. Each element is placed once and each inner node does one combine, so the build is O(n), not O(n log n). There are exactly 2n − 1 nodes.

The nodes live in a flat array, like a heap. With the root at index 1, node i has children 2i and 2i + 1, which is the layout the code uses (with the root at 0, they are 2i + 1 and 2i + 2). No pointers, one allocation.

The array needs 4n slots, not 2n. When n is not a power of two the splits leave holes in the numbering: for n = 6 the deepest leaf sits at index 13, past 2n = 12. Allocating 2n works on powers of two and writes out of bounds on other sizes, a classic bug.

A shorter iterative version keeps the leaves at indexes n to 2n − 1 and fills parents with t[i] = t[2i] + t[2i + 1] from i = n − 1 down to 1. It needs only 2n slots and no recursion, at the cost of being harder to extend with lazy updates.

  • Build is O(n): each of the 2n − 1 nodes is computed once
  • Root at 1: children of i are 2i and 2i + 1
  • Allocate 4n for the recursive layout
3

Range Query and Point Update

A range query for [l, r] starts at the root, and every node it reaches is one of three cases. No overlap: the node's interval is outside [l, r]; return the identity (0 for sum, +∞ for min, −∞ for max). Total overlap: the interval is inside [l, r]; return the stored value without going further down. Partial overlap: ask both children and combine their answers.

Total overlap is where the speed comes from: a whole subtree is answered by one read. On each level at most two nodes partly overlap, one at each end of the range, and everything else stops at once. So a query touches O(log n) nodes, at most four per level.

A point update sets one element: walk down to its leaf, change it, and recompute each ancestor from its two children on the way back. Only the nodes on that one path cover the changed index, so the update is O(log n).

Costs compared
Plain arrayPrefix sumsSegment tree
BuildNoneO(n)O(n)
Range sumO(n)O(1)O(log n)
Point updateO(1)O(n)O(log n)
Range updateO(n)O(n)O(log n) with lazy propagation
Range min or maxO(n)Not possibleO(log n)
Memorynn + 1up to 4n
  • Returning the wrong identity (0 in a min tree) gives wrong answers with no error
  • The query range [l, r] is inclusive at both ends; off-by-one at r is common
  • Indexes start at 0 here; translate 1-based problem input before querying
Key reference

Terms, operations, and practical uses

Tree anatomy

  • Node intervalEach node stores the total (sum, min, max) of one contiguous stretch of the array.
  • RootCovers the whole array, index 0 to n − 1.
  • LeavesIntervals of length 1: the array's elements themselves.

Core operations

  • BuildRecursive, O(n): each node combines its two children once.
  • Range queryNo overlap returns the identity, total overlap returns the node, partial overlap asks both children: O(log n).
  • Point updateChange one leaf and recompute its O(log n) ancestors.

Advanced techniques

  • Lazy propagationA tag on a fully covered node holds a range update until a later visit pushes it to the children.
  • Memory layoutA flat array of 4n slots; with the root at 1, node i's children are 2i and 2i + 1.
  • Dynamic segment treeCreates nodes only when touched, for index ranges as large as 10^9.
Implementation

Code in Python, C++ and Java

class SegmentTree:
    def __init__(self, data):
        self.n = len(data)
        self.tree = [0] * (4 * self.n)
        self.build(data, 1, 0, self.n - 1)
    def build(self, data, node, start, end):
        if start == end:
            self.tree[node] = data[start]
        else:
            mid = (start + end) // 2
            self.build(data, 2 * node, start, mid)
            self.build(data, 2 * node + 1, mid + 1, end)
            self.tree[node] = self.tree[2 * node] + self.tree[2 * node + 1]
    def query(self, node, start, end, l, r):
        if r < start or end < l:
            return 0
        if l <= start and end <= r:
            return self.tree[node]
        mid = (start + end) // 2
        return self.query(2*node, start, mid, l, r) + self.query(2*node+1, mid+1, end, l, r)

tree = SegmentTree([1, 3, 5, 7])
print('sum(1..2) =', tree.query(1, 0, 3, 1, 2))
#include <iostream>
#include <vector>
using namespace std;

class SegmentTree {
    vector<int> tree;
    int n;
    void build(vector<int>& arr, int v, int tl, int tr) {
        if (tl == tr) {
            tree[v] = arr[tl];
        } else {
            int tm = (tl + tr) / 2;
            build(arr, v*2, tl, tm);
            build(arr, v*2+1, tm+1, tr);
            tree[v] = tree[v*2] + tree[v*2+1];
        }
    }
public:
    SegmentTree(vector<int> arr) : tree(4 * arr.size()), n(arr.size()) {
        build(arr, 1, 0, n - 1);
    }
    int query(int v, int tl, int tr, int l, int r) {
        if (r < tl || tr < l) return 0;
        if (l <= tl && tr <= r) return tree[v];
        int tm = (tl + tr) / 2;
        return query(v*2, tl, tm, l, r) + query(v*2+1, tm+1, tr, l, r);
    }
    int size() const { return n; }
};

int main() {
    SegmentTree tree({1, 3, 5, 7});
    cout << "sum(1..2) = " << tree.query(1, 0, tree.size() - 1, 1, 2) << '\n';
}
public class Main {
    static class SegmentTree {
        int[] tree;
        int n;
        SegmentTree(int[] arr) {
            n = arr.length;
            tree = new int[4 * n];
            build(arr, 1, 0, n - 1);
        }
        void build(int[] arr, int v, int tl, int tr) {
            if (tl == tr) {
                tree[v] = arr[tl];
            } else {
                int tm = (tl + tr) / 2;
                build(arr, v*2, tl, tm);
                build(arr, v*2+1, tm+1, tr);
                tree[v] = tree[v*2] + tree[v*2+1];
            }
        }
        int query(int v, int tl, int tr, int l, int r) {
            if (r < tl || tr < l) return 0;
            if (l <= tl && tr <= r) return tree[v];
            int tm = (tl + tr) / 2;
            return query(v*2, tl, tm, l, r) + query(v*2+1, tm+1, tr, l, r);
        }
    }

    public static void main(String[] args) {
        SegmentTree tree = new SegmentTree(new int[]{1, 3, 5, 7});
        System.out.println("sum(1..2) = " + tree.query(1, 0, tree.n - 1, 1, 2));
    }
}
Watch it run

Step through it

Running on SegmentTree([1, 3, 5, 7]); query(1..2)

SegmentTree([1, 3, 5, 7])[0..3]#1–[0..1]#2–[2..3]#3–[0..0]#4–[1..1]#5–[2..2]#6–[3..3]#7–array a1a[0]3a[1]5a[2]7a[3]stored as tree[1..7] (the code allocates 4n = 16 slots)1–2–3–4–5–6–7–n = 4 → 2n − 1 = 7 nodeschildren of #i: #2i and #2i + 1
Step 1

Seven empty nodes over four elements

Each node covers an interval of the array: the root all of [0..3], its children the two halves, the leaves one element each. #i is the node's slot in the flat array; node i's children sit at 2i and 2i + 1.

Output
1 / 14
4

Lazy Propagation

A range update, 'add 5 to every element from l to r', would touch every leaf in the range: O(n). Lazy propagation avoids that by putting off work until something needs it.

When an update covers a node's whole interval, change that node's total, write the pending change into a lazy tag on the node, and stop. Its children are now out of date, but nothing has read them yet.

The rule that comes with it: any later visit that goes below a tagged node first pushes the tag down, applying it to both children, tagging them, and clearing the parent. That push sits at the top of both the query and the update functions; forgetting it is the classic lazy-propagation bug.

For sums, adding v to an interval of length len adds v × len to its total, so each node needs its interval length. For min or max the same update adds just v. Pending additions combine by adding; an 'assign' update overwrites, so trees supporting both store a pair per tag.

  • Fully covered node: update its total, tag it, stop
  • Push the tag down before visiting any child
  • Sum trees scale the pending value by the interval length
5

Choosing a Segment Tree

The tree works with any associative operation (sum, min, max, gcd, bitwise or) because a node's value is just its two children combined. That is its edge over a Fenwick tree, which handles arbitrary ranges only for operations that can be undone, like sum. For a fixed sum, the Fenwick tree is shorter and uses less memory.

If the array never changes and the question is a minimum or maximum, a sparse table answers in O(1) after O(n log n) setup. If the data are intervals rather than positions, an interval tree is the better fit.

Variants worth knowing by name: a merge sort tree keeps a sorted list in each node to count values below x in a range; a persistent segment tree keeps every past version by sharing unchanged nodes; a 2D segment tree answers rectangle queries in O(log² n).

Problems that use the same idea: Count of Smaller Numbers After Self, Reverse Pairs and Count Inversions all become point updates and range counts over value positions.

  • Changing data, range min or max: segment tree
  • Changing data, sums only: Fenwick tree is simpler
  • Data never changes: prefix sums or a sparse table