Lazy propagation
Advanced · 13 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Lazy propagation lets a segment tree change a whole range at once without touching every item. A pending note like "add 2 to everything here" is left on a block and pushed down to its children only when someone actually needs them.
Practical use cases
- Web app: Festive discount on a price range. An admin applies a 10 percent Diwali discount to products 1,000 to 50,000 with one click. Rather than rewriting 49,000 prices, the tree leaves a pending note on a few big blocks. Totals and lowest prices stay correct immediately, and the click returns in a blink.
- Web app: Grace marks for a range of students. A school portal adds 2 marks to every student ranked between 100 and 400. With lazy notes, class totals and topper lists are right at once and no 300-row update loop runs. Teachers see updated rankings immediately, and the database is not hit with 300 single-row updates.
- System: Canvas tools and contests. Painting a stretch of cells in an editor, or contest problems with "add to a range, ask for the sum", use lazy notes so range changes are as cheap as range queries. The pending note is spread to the smaller blocks only when needed, so a bulk change costs about as little as one query.
The story: The Grace Marks Sticky Note
Mrs. Sharma had marked the class test, and the school kept all 8 students' marks in a segment tree: every circle held the total marks of its group, which let the principal ask for any group's total in a blink. Then the board announced grace marks: "Add 2 marks to every student from roll number 0 to 3!" Mrs. Sharma groaned. Updating four leaves and repairing all the circles above was slow. For a school of a hundred thousand students and thousands of announcements, it would take all night.
Grandpa Bhaskar, who had once worked as a post office clerk, smiled. "Beta, we put sticky notes. When the whole group 0-3 is inside the announcement, don't go down to the students. Add 4 students times 2 marks to this group's total, and stick a note on it: my kids still owe +2 each. Do it later, if someone asks."
Nobody asked for a while. Then Zoya wanted to know student 2's marks. On the way down, the circle with the note said, "Wait! First pay the note to my children." Each child took the extra marks and got a note of its own, and so on, only along the road to student 2. This lazy trick is called lazy propagation: range updates become as quick as range queries, because notes are paid down only when someone actually needs the details.
How to spot this problem, and where you need it
You must change a large range of values at once and still answer range questions quickly, but updating each item one by one takes too long.
Signs you need it
- An operation like "add x to every item from a to b" or "set a whole range to x" appears.
- Looping to update each item makes the click, API call or job slow.
- Range queries still need correct answers right after the bulk update.
- The problem says "range update, range query" on one big list.
Where to use it in a project
- Bulk price, tax or stock adjustments on a range of products.
- Grade adjustment, scoring or canvas painting tools that apply the same change to many items.
The solution
Add a "pending change" field to each tree node. For a range update, apply the change to the few blocks that fully fit the range, fix their stored answers and leave a pending note for their children. Whenever a later query or update must go below a block, first push its note down to the two children. Work is only done where needed.
Payoff: Before: updating 49,000 items one by one. After: touching about 40 blocks and leaving notes for later.
Explain it like I am 8
You tell your mum, "Please add 2 sweets to each of the first four jars." Instead of walking to every jar, she writes on a sticky note on the big shelf: "+2 each". Whenever someone opens one jar from that shelf, she first adds the sweets to the jar. Notes wait until the details are needed.
How it works, step by step
- Each circle keeps two things: its total, and a "lazy note" saying how much still has to be added to each person below.
- Range update: if a circle is entirely inside the range, add
value x (number of items in it)to its total, add the value to its note, and stop right there. - If it is only partly inside, first push down any note to the children, recurse into both children, and then recompute the total from them.
- Push down means: add the note to each child's total (times the child's size), add it to the child's note, and clear your own note.
- Queries also push notes down before going into children, so they never read stale numbers.
The code in four languages
PHP
<?php
// Range ADD + range SUM with lazy notes
class LazySeg {
private array $sum;
private array $lazy; // pending "+v for each item below me"
private int $n;
public function __construct(array $a) {
$this->n = count($a);
$this->sum = array_fill(0, 4 * $this->n, 0);
$this->lazy = 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->sum[$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->sum[$node] = $this->sum[2 * $node] + $this->sum[2 * $node + 1];
}
// Put v on this circle: its total grows by v x (number of items), and a note is stuck
private function apply(int $node, int $l, int $r, int $v): void {
$this->sum[$node] += $v * ($r - $l + 1);
$this->lazy[$node] += $v;
}
// Pay the note forward to both children
private function push(int $node, int $l, int $r): void {
if ($this->lazy[$node] === 0) return;
$m = intdiv($l + $r, 2);
$this->apply(2 * $node, $l, $m, $this->lazy[$node]);
$this->apply(2 * $node + 1, $m + 1, $r, $this->lazy[$node]);
$this->lazy[$node] = 0;
}
public function add(int $ql, int $qr, int $v, int $node = 1, int $l = 0, ?int $r = null): void {
$r ??= $this->n - 1;
if ($qr < $l || $r < $ql) return; // outside
if ($ql <= $l && $r <= $qr) { $this->apply($node, $l, $r, $v); return; } // inside: just a note
$this->push($node, $l, $r); // partly: pay old notes first
$m = intdiv($l + $r, 2);
$this->add($ql, $qr, $v, 2 * $node, $l, $m);
$this->add($ql, $qr, $v, 2 * $node + 1, $m + 1, $r);
$this->sum[$node] = $this->sum[2 * $node] + $this->sum[2 * $node + 1];
}
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;
if ($ql <= $l && $r <= $qr) return $this->sum[$node];
$this->push($node, $l, $r); // never read below a pending note
$m = intdiv($l + $r, 2);
return $this->query($ql, $qr, 2 * $node, $l, $m) + $this->query($ql, $qr, 2 * $node + 1, $m + 1, $r);
}
}
$marks = new LazySeg([5, 3, 7, 2, 6, 4, 1, 8]);
$marks->add(0, 3, 2); // grace marks: +2 for students 0..3
echo $marks->query(0, 7) . PHP_EOL; // 36 + 8 = 44
echo $marks->query(2, 2) . PHP_EOL; // 7 + 2 = 9
echo $marks->query(1, 5) . PHP_EOL; // 5+9+4+6+4 = 28JavaScript
// Range ADD + range SUM with lazy notes
class LazySeg {
constructor(a) {
this.n = a.length;
this.sum = new Array(4 * this.n).fill(0);
this.lazy = new Array(4 * this.n).fill(0); // pending "+v for each item below me"
this.build(a, 1, 0, this.n - 1);
}
build(a, node, l, r) {
if (l === r) { this.sum[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.sum[node] = this.sum[2 * node] + this.sum[2 * node + 1];
}
// Put v on this circle: its total grows by v x (number of items), and a note is stuck
apply(node, l, r, v) {
this.sum[node] += v * (r - l + 1);
this.lazy[node] += v;
}
// Pay the note forward to both children
push(node, l, r) {
if (this.lazy[node] === 0) return;
const m = (l + r) >> 1;
this.apply(2 * node, l, m, this.lazy[node]);
this.apply(2 * node + 1, m + 1, r, this.lazy[node]);
this.lazy[node] = 0;
}
add(ql, qr, v, node = 1, l = 0, r = this.n - 1) {
if (qr < l || r < ql) return; // outside
if (ql <= l && r <= qr) { this.apply(node, l, r, v); return; } // inside: just a note
this.push(node, l, r); // partly: pay old notes first
const m = (l + r) >> 1;
this.add(ql, qr, v, 2 * node, l, m);
this.add(ql, qr, v, 2 * node + 1, m + 1, r);
this.sum[node] = this.sum[2 * node] + this.sum[2 * node + 1];
}
query(ql, qr, node = 1, l = 0, r = this.n - 1) {
if (qr < l || r < ql) return 0;
if (ql <= l && r <= qr) return this.sum[node];
this.push(node, l, r); // never read below a pending note
const m = (l + r) >> 1;
return this.query(ql, qr, 2 * node, l, m) + this.query(ql, qr, 2 * node + 1, m + 1, r);
}
}
const marks = new LazySeg([5, 3, 7, 2, 6, 4, 1, 8]);
marks.add(0, 3, 2); // grace marks: +2 for students 0..3
console.log(marks.query(0, 7)); // 36 + 8 = 44
console.log(marks.query(2, 2)); // 7 + 2 = 9
console.log(marks.query(1, 5)); // 5+9+4+6+4 = 28Java
public class Main {
// Range ADD + range SUM with lazy notes
static class LazySeg {
int[] sum;
int[] lazy; // pending "+v for each item below me"
int n;
LazySeg(int[] a) {
n = a.length;
sum = new int[4 * n];
lazy = new int[4 * n];
build(a, 1, 0, n - 1);
}
void build(int[] a, int node, int l, int r) {
if (l == r) { sum[node] = a[l]; return; }
int m = (l + r) / 2;
build(a, 2 * node, l, m);
build(a, 2 * node + 1, m + 1, r);
sum[node] = sum[2 * node] + sum[2 * node + 1];
}
// Put v on this circle: its total grows by v x (number of items), and a note is stuck
void apply(int node, int l, int r, int v) {
sum[node] += v * (r - l + 1);
lazy[node] += v;
}
// Pay the note forward to both children
void push(int node, int l, int r) {
if (lazy[node] == 0) return;
int m = (l + r) / 2;
apply(2 * node, l, m, lazy[node]);
apply(2 * node + 1, m + 1, r, lazy[node]);
lazy[node] = 0;
}
void add(int ql, int qr, int v) { add(ql, qr, v, 1, 0, n - 1); }
void add(int ql, int qr, int v, int node, int l, int r) {
if (qr < l || r < ql) return; // outside
if (ql <= l && r <= qr) { apply(node, l, r, v); return; } // inside: just a note
push(node, l, r); // partly: pay old notes first
int m = (l + r) / 2;
add(ql, qr, v, 2 * node, l, m);
add(ql, qr, v, 2 * node + 1, m + 1, r);
sum[node] = sum[2 * node] + sum[2 * node + 1];
}
int query(int ql, int qr) { return query(ql, qr, 1, 0, n - 1); }
int query(int ql, int qr, int node, int l, int r) {
if (qr < l || r < ql) return 0;
if (ql <= l && r <= qr) return sum[node];
push(node, l, r); // never read below a pending note
int m = (l + r) / 2;
return query(ql, qr, 2 * node, l, m) + query(ql, qr, 2 * node + 1, m + 1, r);
}
}
public static void main(String[] args) {
LazySeg marks = new LazySeg(new int[]{5, 3, 7, 2, 6, 4, 1, 8});
marks.add(0, 3, 2); // grace marks: +2 for students 0..3
System.out.println(marks.query(0, 7)); // 36 + 8 = 44
System.out.println(marks.query(2, 2)); // 7 + 2 = 9
System.out.println(marks.query(1, 5)); // 5+9+4+6+4 = 28
}
}Go
package main
import "fmt"
// LazySeg supports range ADD + range SUM with lazy notes.
type LazySeg struct {
sum []int
lazy []int // pending "+v for each item below me"
n int
}
func NewLazySeg(a []int) *LazySeg {
s := &LazySeg{sum: make([]int, 4*len(a)), lazy: make([]int, 4*len(a)), n: len(a)}
s.build(a, 1, 0, s.n-1)
return s
}
func (s *LazySeg) build(a []int, node, l, r int) {
if l == r {
s.sum[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.sum[node] = s.sum[2*node] + s.sum[2*node+1]
}
// apply puts v on this circle: its total grows by v x (number of items), and a note is stuck.
func (s *LazySeg) apply(node, l, r, v int) {
s.sum[node] += v * (r - l + 1)
s.lazy[node] += v
}
// push pays the note forward to both children.
func (s *LazySeg) push(node, l, r int) {
if s.lazy[node] == 0 {
return
}
m := (l + r) / 2
s.apply(2*node, l, m, s.lazy[node])
s.apply(2*node+1, m+1, r, s.lazy[node])
s.lazy[node] = 0
}
func (s *LazySeg) Add(ql, qr, v int) { s.add(ql, qr, v, 1, 0, s.n-1) }
func (s *LazySeg) add(ql, qr, v, node, l, r int) {
if qr < l || r < ql { // outside
return
}
if ql <= l && r <= qr { // inside: just a note
s.apply(node, l, r, v)
return
}
s.push(node, l, r) // partly: pay old notes first
m := (l + r) / 2
s.add(ql, qr, v, 2*node, l, m)
s.add(ql, qr, v, 2*node+1, m+1, r)
s.sum[node] = s.sum[2*node] + s.sum[2*node+1]
}
func (s *LazySeg) Query(ql, qr int) int { return s.query(ql, qr, 1, 0, s.n-1) }
func (s *LazySeg) query(ql, qr, node, l, r int) int {
if qr < l || r < ql {
return 0
}
if ql <= l && r <= qr {
return s.sum[node]
}
s.push(node, l, r) // never read below a pending note
m := (l + r) / 2
return s.query(ql, qr, 2*node, l, m) + s.query(ql, qr, 2*node+1, m+1, r)
}
func main() {
marks := NewLazySeg([]int{5, 3, 7, 2, 6, 4, 1, 8})
marks.Add(0, 3, 2) // grace marks: +2 for students 0..3
fmt.Println(marks.Query(0, 7)) // 36 + 8 = 44
fmt.Println(marks.Query(2, 2)) // 7 + 2 = 9
fmt.Println(marks.Query(1, 5)) // 5+9+4+6+4 = 28
}Time: O(log n) per range update and per query · Extra space: O(n). Notes are left waiting on big circles and paid down only along the path that someone asks about.
Watch out for
- Forgetting to push the note down before visiting the children, so you read or change stale values.
- Adding the value to a circle's total without multiplying by how many items the circle covers.
- Not clearing the note after pushing it down, so the same marks get paid twice.
Quick check
- A circle for 4 students receives "+2 each". How much does its total grow?
- 2
- 8
- 4
- When is a lazy note pushed to the children?
- Immediately when it is created
- Never
- When a later operation needs to go below that circle
- What does lazy propagation make fast?
- Updating a whole range at once
- Sorting the array
- Printing the tree