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.
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
// 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;
}
} class SegTree:
"""Max segment tree, iterative: set one position, query the max of [l, r]."""
def __init__(self, n):
self.n = n
self.t = [0] * (2 * n) # leaves live at t[n..2n-1]; every value starts at 0
def update(self, i, v):
i += self.n
self.t[i] = v
while i > 1: # fix the parents
i //= 2
self.t[i] = max(self.t[2 * i], self.t[2 * i + 1])
def query(self, l, r): # inclusive range, l <= r
res = float('-inf')
l += self.n
r += self.n + 1
while l < r:
if l & 1:
res = max(res, self.t[l]); l += 1
if r & 1:
r -= 1; res = max(res, self.t[r])
l //= 2; r //= 2
return res // max segment tree, iterative: set one position, query the max of [l, r]
struct SegTree {
int n;
vector<int> t; // leaves live at t[n..2n-1]; every value starts at 0
SegTree(int n) : n(n), t(2 * n, 0) {}
void update(int i, int v) {
for (t[i += n] = v; i > 1; i >>= 1) t[i >> 1] = max(t[i], t[i ^ 1]); // fix the parents
}
int query(int l, int r) { // inclusive range, l <= r
int res = INT_MIN;
for (l += n, r += n + 1; l < r; l >>= 1, r >>= 1) {
if (l & 1) res = max(res, t[l++]);
if (r & 1) res = max(res, t[--r]);
}
return res;
}
}; // max segment tree, iterative: set one position, query the max of [l, r]
class SegTree {
constructor(n) {
this.n = n;
this.t = new Array(2 * n).fill(0); // leaves live at t[n..2n-1]; every value starts at 0
}
update(i, v) {
const t = this.t;
for (t[i += this.n] = v; i > 1; i >>= 1) t[i >> 1] = Math.max(t[i], t[i ^ 1]); // fix the parents
}
query(l, r) { // inclusive range, l <= r
let res = -Infinity;
for (l += this.n, r += this.n + 1; l < r; l >>= 1, r >>= 1) {
if (l & 1) res = Math.max(res, this.t[l++]);
if (r & 1) res = Math.max(res, this.t[--r]);
}
return res;
}
} The variations
-
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.
Lesson done
Back to Intervals →Mark it done once you can write the template from memory and you have solved the worked examples yourself.