Query
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A segment tree query answers a range question by combining only a few stored blocks. Blocks fully inside the range are read directly, blocks fully outside are ignored, and only blocks that partly overlap are split further.
Practical use cases
- Web app: Peak CPU in the last hour. A server dashboard shows the highest CPU use between any two times chosen on the chart. The query reads a handful of stored blocks covering the window and picks the maximum, rather than scanning 3,600 readings each time. The engineer drags the chart window and the maximum number follows the cursor without any visible delay.
- Web app: Lowest price in a date range. A price-tracker page shows the cheapest price a product had between two dates picked on a slider. Each slider move runs a quick query, so the answer keeps pace with the mouse. The slider feels instant even with ten years of daily prices behind it.
- System: Monitoring systems and geometry. Alerting tools check extremes over time windows, and geometry code checks ranges of coordinates; both use these three rules: inside, outside, or split. Because only blocks on the edges of the range are split, the number of steps stays small even for huge data.
The story: Three Rules at the Cloakroom
At the busy railway station, Raju's cousin Imran runs the cloakroom. There are 8 shelves, and for every group of shelves a little card shows how many bags it holds: one card for the first four shelves, one for the last four, one for each pair, and so on. It is a segment tree, built last time.
A traveller asks, "How many bags on shelves 2 to 5?" Imran starts at the biggest card, shelves 0 to 7, and thinks with three simple rules. Rule one: if none of this card's shelves are in the question, it adds nothing, so skip it. Rule two: if all of this card's shelves are inside the question, take its number whole. Do not open the shelves. Rule three: if only some are inside, ask the two smaller cards below it and add their answers.
The result surprised the traveller. Out of fifteen cards Imran touched only seven, and combined just two numbers: shelves 2-3 and shelves 4-5. Even for a million shelves, Imran would need only a few dozen cards, because at every level at most a couple of cards are "partly inside". That is the segment tree query.
How to spot this problem, and where you need it
Users choose arbitrary ranges and you need a sum, minimum or maximum for each, but scanning the range every time makes the page lag.
Signs you need it
- The UI has a slider, date range or selection that triggers a new answer on every change.
- You compute the answer with a loop from the start to the end of the range.
- The data volume is large (tens of thousands of points or more).
- The problem says "answer many range queries" over one large list.
Where to use it in a project
- Time-series charts with zoom or brush selection by users.
- Price, temperature or traffic trackers that report extremes for chosen periods.
The solution
Start at the root with the range you want. If a node's block lies completely inside the range, take its stored answer. If it lies completely outside, ignore it. If it partly overlaps, ask both children and combine their answers. Only blocks on the two edges of the range ever get split, so very few nodes are visited.
Payoff: Before: scanning 3,600 readings per slider move. After: reading about 20 blocks.
Explain it like I am 8
You want to know how many marbles are in boxes 3 to 6. Big boxes contain smaller boxes. If a big box lies completely inside boxes 3 to 6, just read its label. If it is completely outside, ignore it. If it only half overlaps, open it and look at the two smaller boxes inside.
How it works, step by step
- Begin at the root with the question range (ql to qr).
- Outside rule: the circle's stretch does not touch the question, so return the "nothing" value (0 for sums).
- Inside rule: the circle's stretch is entirely in the question, so return its stored value at once.
- Partly rule: the stretch overlaps only partly, so ask the left child, ask the right child, and combine.
- Why it is fast: at each level only a couple of circles are partly inside; the rest are decided immediately.
The code in four languages
PHP
<?php
class SegTree {
private array $t;
private int $n;
public function __construct(array $a) {
$this->n = count($a);
$this->t = array_fill(0, 4 * $this->n, 0);
$this->build($a, 1, 0, $this->n - 1);
}
private function build(array $a, int $node, int $l, int $r): void {
if ($l === $r) { $this->t[$node] = $a[$l]; return; }
$m = intdiv($l + $r, 2);
$this->build($a, 2 * $node, $l, $m);
$this->build($a, 2 * $node + 1, $m + 1, $r);
$this->t[$node] = $this->t[2 * $node] + $this->t[2 * $node + 1];
}
// Sum of positions ql..qr. This card covers positions l..r.
public function query(int $ql, int $qr, int $node = 1, int $l = 0, ?int $r = null): int {
$r ??= $this->n - 1;
if ($qr < $l || $r < $ql) return 0; // outside: adds nothing
if ($ql <= $l && $r <= $qr) return $this->t[$node]; // inside: take it whole
$m = intdiv($l + $r, 2); // partly: ask both children
return $this->query($ql, $qr, 2 * $node, $l, $m)
+ $this->query($ql, $qr, 2 * $node + 1, $m + 1, $r);
}
}
$bags = new SegTree([5, 3, 7, 2, 6, 4, 1, 8]);
echo $bags->query(2, 5) . PHP_EOL; // 7+2+6+4 = 19
echo $bags->query(0, 7) . PHP_EOL; // 36, the root alone
echo $bags->query(3, 3) . PHP_EOL; // 2, a single shelfJavaScript
class SegTree {
constructor(a) {
this.n = a.length;
this.t = new Array(4 * this.n).fill(0);
this.build(a, 1, 0, this.n - 1);
}
build(a, node, l, r) {
if (l === r) { this.t[node] = a[l]; return; }
const m = (l + r) >> 1;
this.build(a, 2 * node, l, m);
this.build(a, 2 * node + 1, m + 1, r);
this.t[node] = this.t[2 * node] + this.t[2 * node + 1];
}
// Sum of positions ql..qr. This card covers positions l..r.
query(ql, qr, node = 1, l = 0, r = this.n - 1) {
if (qr < l || r < ql) return 0; // outside: adds nothing
if (ql <= l && r <= qr) return this.t[node]; // inside: take it whole
const m = (l + r) >> 1; // partly: ask both children
return this.query(ql, qr, 2 * node, l, m)
+ this.query(ql, qr, 2 * node + 1, m + 1, r);
}
}
const bags = new SegTree([5, 3, 7, 2, 6, 4, 1, 8]);
console.log(bags.query(2, 5)); // 7+2+6+4 = 19
console.log(bags.query(0, 7)); // 36, the root alone
console.log(bags.query(3, 3)); // 2, a single shelfJava
public class Main {
static class SegTree {
int[] t;
int n;
SegTree(int[] a) {
n = a.length;
t = new int[4 * n];
build(a, 1, 0, n - 1);
}
void build(int[] a, int node, int l, int r) {
if (l == r) { t[node] = a[l]; return; }
int m = (l + r) / 2;
build(a, 2 * node, l, m);
build(a, 2 * node + 1, m + 1, r);
t[node] = t[2 * node] + t[2 * node + 1];
}
// Sum of positions ql..qr, asked at the root card (it covers 0..n-1).
int query(int ql, int qr) {
return query(ql, qr, 1, 0, n - 1);
}
// Sum of positions ql..qr. This card covers positions l..r.
int query(int ql, int qr, int node, int l, int r) {
if (qr < l || r < ql) return 0; // outside: adds nothing
if (ql <= l && r <= qr) return t[node]; // inside: take it whole
int m = (l + r) / 2; // partly: ask both children
return query(ql, qr, 2 * node, l, m)
+ query(ql, qr, 2 * node + 1, m + 1, r);
}
}
public static void main(String[] args) {
SegTree bags = new SegTree(new int[]{5, 3, 7, 2, 6, 4, 1, 8});
System.out.println(bags.query(2, 5)); // 7+2+6+4 = 19
System.out.println(bags.query(0, 7)); // 36, the root alone
System.out.println(bags.query(3, 3)); // 2, a single shelf
}
}Go
package main
import "fmt"
type SegTree struct {
t []int
n int
}
func NewSegTree(a []int) *SegTree {
s := &SegTree{t: make([]int, 4*len(a)), n: len(a)}
s.build(a, 1, 0, s.n-1)
return s
}
func (s *SegTree) build(a []int, node, l, r int) {
if l == r {
s.t[node] = a[l]
return
}
m := (l + r) / 2
s.build(a, 2*node, l, m)
s.build(a, 2*node+1, m+1, r)
s.t[node] = s.t[2*node] + s.t[2*node+1]
}
// Query returns the sum of positions ql..qr, asked at the root card (it covers 0..n-1).
func (s *SegTree) Query(ql, qr int) int {
return s.query(ql, qr, 1, 0, s.n-1)
}
// query sums positions ql..qr. This card covers positions l..r.
func (s *SegTree) query(ql, qr, node, l, r int) int {
if qr < l || r < ql { // outside: adds nothing
return 0
}
if ql <= l && r <= qr { // inside: take it whole
return s.t[node]
}
m := (l + r) / 2 // partly: ask both children
return s.query(ql, qr, 2*node, l, m) +
s.query(ql, qr, 2*node+1, m+1, r)
}
func main() {
bags := NewSegTree([]int{5, 3, 7, 2, 6, 4, 1, 8})
fmt.Println(bags.Query(2, 5)) // 7+2+6+4 = 19
fmt.Println(bags.Query(0, 7)) // 36, the root alone
fmt.Println(bags.Query(3, 3)) // 2, a single shelf
}Time: O(log n) per query · Extra space: O(n). At each level of the tree at most about two circles are "partly inside", so the walk stays short even for a huge row.
Watch out for
- Checking "inside" before "outside" with sloppy conditions, which lets partly-overlapping circles slip through.
- Returning 0 for "outside" when the job is a minimum. Use a value that can never win, such as infinity.
- Mixing inclusive and exclusive ends. Pick inclusive for both the question and the circle stretch and keep it everywhere.
Quick check
- A circle covers shelves 0-3, and the question is shelves 2-5. Which rule applies?
- Outside
- Inside
- Partly, so ask both children
- What do we return for a circle completely outside the question?
- Its stored total
- An error
- The nothing value (0 for sums)
- Why does the query stay quick?
- It scans only the asked shelves
- Most circles are decided immediately; only a couple per level go deeper
- It sorts the data first