Intervals · Pattern 3 of 3

Segment tree: range queries while intervals change

A segment tree keeps the max (or sum) of every block of positions, so you can change one position and ask about any range in O(log n). Use it when updates and range questions are mixed.

1 variation · 1 problem

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Updates and range queries arrive mixed together
  • The largest gap or value in a prefix or range, after every change
  • A plain prefix sum would need rebuilding after each update

The template

Segment Tree
// max segment tree, iterative: set one position, query the max of [l, r]
class SegTree {
    int n;
    int[] t;                                  // leaves live at t[n..2n-1]; every value starts at 0
    SegTree(int n) { this.n = n; t = new int[2 * n]; }
    void update(int i, int v) {
        for (t[i += n] = v; i > 1; i >>= 1) t[i >> 1] = Math.max(t[i], t[i ^ 1]);   // fix the parents
    }
    int query(int l, int r) {                 // inclusive range, l <= r
        int res = Integer.MIN_VALUE;
        for (l += n, r += n + 1; l < r; l >>= 1, r >>= 1) {
            if ((l & 1) == 1) res = Math.max(res, t[l++]);
            if ((r & 1) == 1) res = Math.max(res, t[--r]);
        }
        return res;
    }
}

The variations

  1. 1Largest free gap in a prefix

    Store, at each obstacle position, the gap back to the previous obstacle. A sorted set finds the neighbours of a new obstacle, and the tree updates the two gaps that change. For a query at x, the largest gap is the tree max up to the last obstacle at or before x, compared with x minus that obstacle.

Mistakes to avoid

  • Mixing inclusive and exclusive range ends between the call and the loop: pick one and convert once.
  • Forgetting the part of the range after the last obstacle: in block placement, the gap from the last obstacle at or before x up to x is not stored in the tree.
  • Sizing the tree by the number of queries instead of the largest coordinate.
Back to Intervals →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.