Update
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Updating a segment tree changes one leaf and then fixes only the blocks above it that depended on that leaf, going up one level at a time to the root. Everything else is left alone, so the tree stays correct with a few steps of work.
Practical use cases
- Web app: Price tick on a trading screen. A stock page receives a new price for one share. The app updates that share's leaf and recalculates its parent, grandparent and so on, about 17 blocks, so "highest price today" and sector totals stay right while hundreds of ticks arrive per second.
- Web app: Live inventory with range totals. When a customer buys item 4,512, the stock count for that item drops by one. The tree fixes only the blocks that include it, so the "total in category" numbers stay correct without recomputing the entire catalogue. Each purchase therefore costs a handful of small recalculations, instead of a rebuild of every category total in the shop.
- System: Leaderboards and contest problems. Leaderboards that show best scores in a bracket and contest problems with "change a value, then query" both rely on fixing just the path from leaf to root. Both stay fast no matter how many updates arrive, because only one path in the tree is ever repaired.
The story: The Stale Sticky Notes
Aarav's family runs a kirana store with 8 bins of rice, dal and sugar in a row. On the wall behind the counter, Aarav's father stuck neat sticky notes: one for each pair of bins, one for each group of four, and one at the very top for the whole store. The notes saved him from counting, and customers got fast answers.
Then a truck arrived with a delivery for bin 3. The stock in that bin jumped from 2 kg to 9 kg. Aarav panicked: "Papa, do we rewrite all the sticky notes?" Papa smiled. "Only the notes that include bin 3 are wrong. That is the note for bins 2-3, the note for bins 0-3, and the note for everything. The other notes never mention bin 3."
So Aarav fixed bin 3, then walked up: recompute the 2-3 note from its two children, then the 0-3 note, then the top. Four fixes, not fifteen. In tree language, an update changes one leaf and repairs the path from that leaf up to the root, and that path is always short. This is the segment tree update: the reason the tree beats a prefix array when numbers keep changing.
How to spot this problem, and where you need it
Individual values change often and you must keep range answers up to date, but rebuilding the whole summary after each change is far too slow.
Signs you need it
- Rebuilding your summary on every change makes the page or API visibly slow.
- Each change affects one item but you recompute data about all items.
- Updates and queries are interleaved at high rates, such as live prices or stock.
- The problem says "update one element, then answer range queries".
Where to use it in a project
- Trading, inventory and scoreboard features that change many times per second.
- Dashboards fed by streams of single-record updates from many sources.
The solution
Find the leaf for the changed position and set its new value. Then move to its parent and recalculate it from its two children (sum, min or max), then to the grandparent, and so on up to the root. Only the blocks on that single upward path were out of date, so only they are redone.
Payoff: Before: rebuilding 100,000 stored answers per change. After: about 17 recalculations.
Explain it like I am 8
Imagine a family tree of cards where every grown-up card shows the total of their kids. If one kid's number changes, only that kid's parent, grandparent and great-grandparent cards go out of date. Fix them one by one on the way up and everything is correct again.
How it works, step by step
- Go down from the root toward the position, always choosing the half that contains it.
- At the single-item circle, overwrite the stored value with the new one.
- Come back up. After returning from a child, recompute the circle from its two children:
left + right. - Stop at the root. Only the circles on that one path were touched.
- Cost: as many steps as the tree is tall, which grows very slowly with n.
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];
}
// Set position $pos to $value
public function update(int $pos, int $value, int $node = 1, int $l = 0, ?int $r = null): void {
$r ??= $this->n - 1;
if ($l === $r) { // reached the bin itself
$this->t[$node] = $value;
return;
}
$m = intdiv($l + $r, 2);
if ($pos <= $m) $this->update($pos, $value, 2 * $node, $l, $m); // go to the half that holds pos
else $this->update($pos, $value, 2 * $node + 1, $m + 1, $r);
$this->t[$node] = $this->t[2 * $node] + $this->t[2 * $node + 1]; // repair on the way back up
}
public function total(): int { return $this->t[1]; }
}
$stock = new SegTree([5, 3, 7, 2, 6, 4, 1, 8]);
echo $stock->total() . PHP_EOL; // 36
$stock->update(3, 9); // bin 3: 2 kg -> 9 kg
echo $stock->total() . PHP_EOL; // 43JavaScript
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];
}
// Set position pos to value
update(pos, value, node = 1, l = 0, r = this.n - 1) {
if (l === r) { // reached the bin itself
this.t[node] = value;
return;
}
const m = (l + r) >> 1;
if (pos <= m) this.update(pos, value, 2 * node, l, m); // go to the half that holds pos
else this.update(pos, value, 2 * node + 1, m + 1, r);
this.t[node] = this.t[2 * node] + this.t[2 * node + 1]; // repair on the way back up
}
total() { return this.t[1]; }
}
const stock = new SegTree([5, 3, 7, 2, 6, 4, 1, 8]);
console.log(stock.total()); // 36
stock.update(3, 9); // bin 3: 2 kg -> 9 kg
console.log(stock.total()); // 43Java
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];
}
// Set position pos to value
void update(int pos, int value) {
update(pos, value, 1, 0, n - 1);
}
void update(int pos, int value, int node, int l, int r) {
if (l == r) { // reached the bin itself
t[node] = value;
return;
}
int m = (l + r) / 2;
if (pos <= m) update(pos, value, 2 * node, l, m); // go to the half that holds pos
else update(pos, value, 2 * node + 1, m + 1, r);
t[node] = t[2 * node] + t[2 * node + 1]; // repair on the way back up
}
int total() { return t[1]; }
}
public static void main(String[] args) {
SegTree stock = new SegTree(new int[]{5, 3, 7, 2, 6, 4, 1, 8});
System.out.println(stock.total()); // 36
stock.update(3, 9); // bin 3: 2 kg -> 9 kg
System.out.println(stock.total()); // 43
}
}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]
}
// Update sets position pos to value.
func (s *SegTree) Update(pos, value int) {
s.update(pos, value, 1, 0, s.n-1)
}
func (s *SegTree) update(pos, value, node, l, r int) {
if l == r { // reached the bin itself
s.t[node] = value
return
}
m := (l + r) / 2
if pos <= m { // go to the half that holds pos
s.update(pos, value, 2*node, l, m)
} else {
s.update(pos, value, 2*node+1, m+1, r)
}
s.t[node] = s.t[2*node] + s.t[2*node+1] // repair on the way back up
}
func (s *SegTree) Total() int { return s.t[1] }
func main() {
stock := NewSegTree([]int{5, 3, 7, 2, 6, 4, 1, 8})
fmt.Println(stock.Total()) // 36
stock.Update(3, 9) // bin 3: 2 kg -> 9 kg
fmt.Println(stock.Total()) // 43
}Time: O(log n) per update · Extra space: O(n). The repaired path has one circle per level of the tree, so even a million bins need only about twenty repairs.
Watch out for
- Recomputing the ancestors before the child is fixed. Repair on the way back up, after the recursive call returns.
- Updating the leaf but forgetting the ancestors, so range answers silently use stale totals.
- Rebuilding the whole tree after every change, which turns a quick update into slow O(n) work.
Quick check
- Bin 3 changes. Which circles must be recomputed?
- All 15
- Only the root
- Only the circles whose stretch includes bin 3
- In which order are the circles repaired?
- Top to bottom
- Bottom to top, after the child is fixed
- In random order
- How many circles does one update touch?
- Half the tree
- Every leaf
- Just the ones on one root-to-leaf path