Advanced Data Structures · 15 min · free lesson

Lazy Segment Tree: When to Use It

Recognise the problem shape before choosing Lazy Segment Tree.

Core idea

An addition already included in this node's sum but not yet pushed to children. State the input preconditions before applying this invariant.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Store pending range operations at covering nodes and push them only before descending.

O(log n) update/query · O(n) space242 execution steps
main · before line 80Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputvalues=[1,2,3,4,5,6]

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 80
struct LazySum {
    sum: Vec<i64>,
    lazy: Vec<i64>,
    n: usize,
}
impl LazySum {
    fn new(values: &[i64]) -> Self {
        let n = values.len();
        assert!(n > 0);
        let mut tree = Self {
            sum: vec![0; 4 * n],
            lazy: vec![0; 4 * n],
            n,
        };
        fn build(t: &mut LazySum, v: usize, left: usize, right: usize, a: &[i64]) {
            if right - left == 1 {
                t.sum[v] = a[left];
            } else {
                let mid = (left + right) / 2;
                build(t, v * 2, left, mid, a);
                build(t, v * 2 + 1, mid, right, a);
                t.sum[v] = t.sum[v * 2] + t.sum[v * 2 + 1];
            }
        }
        build(&mut tree, 1, 0, n, values);
        tree
    }
    fn apply(&mut self, v: usize, length: usize, delta: i64) {
        self.sum[v] += delta * length as i64;
        self.lazy[v] += delta;
    }
    fn push(&mut self, v: usize, left: usize, right: usize) {
        if right - left > 1 {
            let mid = (left + right) / 2;
            let d = self.lazy[v];
            self.apply(v * 2, mid - left, d);
            self.apply(v * 2 + 1, right - mid, d);
        }
        self.lazy[v] = 0;
    }
    fn update(&mut self, v: usize, left: usize, right: usize, from: usize, to: usize, delta: i64) {
        if to <= left || right <= from {
            return;
        }
        if from <= left && right <= to {
            self.apply(v, right - left, delta);
            return;
        }
        self.push(v, left, right);
        let mid = (left + right) / 2;
        self.update(v * 2, left, mid, from, to, delta);
        self.update(v * 2 + 1, mid, right, from, to, delta);
        self.sum[v] = self.sum[v * 2] + self.sum[v * 2 + 1];
    }
    fn query(&mut self, v: usize, left: usize, right: usize, from: usize, to: usize) -> i64 {
        if to <= left || right <= from {
            return 0;
        }
        if from <= left && right <= to {
            return self.sum[v];
        }
        self.push(v, left, right);
        let mid = (left + right) / 2;
        self.query(v * 2, left, mid, from, to) + self.query(v * 2 + 1, mid, right, from, to)
    }
    fn add(&mut self, left: usize, right: usize, delta: i64) {
        self.update(1, 0, self.n, left, right + 1, delta);
    }
    fn range_sum(&mut self, left: usize, right: usize) -> i64 {
        self.query(1, 0, self.n, left, right + 1)
    }
}
fn lazy_example(values: &[i64]) -> i64 {
    let mut tree = LazySum::new(values);
    tree.add(1, 4, 3);
    tree.range_sum(2, 5)
}
 
fn main() {
    let result = lazy_example(&[1, 2, 3, 4, 5, 6]).to_string();
    println!("{result}");
}

Try your own version

Compare the visible input `values=[1,2,3,4,5,6]` with `values=[9,8,7,6,5,4]`. Predict why their results are `27` and `31`. Then change one legal value and explain whether the same invariant, an addition already included in this node's sum but not yet pushed to children, still applies.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Advanced Data Structures infographic; panel 3 illustrates Lazy Segment Tree.
Lazy Segment Tree: follow panel 3 to see the operation, then trace this lesson's example.

Understand it

Add 3 to inclusive [1,4] of [1,2,3,4,5,6], giving [1,5,6,7,8,6]. Query [2,5] returns 27. A fully covered segment adds delta times segment length; partial descent pushes pending tags first.

The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Add 3 to inclusive indexes 1..4, then return the sum of inclusive indexes 2..5. Input contains at least six integers. The visible fixture is values=[1,2,3,4,5,6] and its example result is 27. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.

Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.

String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

A problem is a good match for Lazy Segment Tree when it asks for range updates plus range aggregate queries. Here the concrete task is: Add 3 to inclusive indexes 1..4, then return the sum of inclusive indexes 2..5. Input contains at least six integers. The visible input values=[1,2,3,4,5,6] is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Choose it when the required operation sequence, query volume, or substring structure exceeds a simple scan or prefix summary; compare the real time and memory limits first. The right choice follows from those guarantees, not from a familiar noun in the prompt.

The decisive invariant is: Store pending range operations at covering nodes and push them only before descending. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? An advanced structure or offline query order packages an invariant across operations. Name what each node, block, or reordered query state stores. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.

Compare costs before committing. The advertised bound is O(log n) update/query · O(n) space; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 27 and explain which part of the state lets the method reach that result.

When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Test empty ranges, repeated updates, undo operations where supported, and the exact boundary between adjacent blocks. Keep representation and operations separate in Rust. Verify a tiny instance against a straightforward reference implementation before optimizing. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.

The pattern

Store pending range operations at covering nodes and push them only before descending.

When to use it: range updates plus range aggregate queries

Complexity: O(log n) update/query · O(n) space

Input: values=[1,2,3,4,5,6]

Read the code

struct LazySum {
    sum: Vec<i64>,
    lazy: Vec<i64>,
    n: usize,
}
impl LazySum {
    fn new(values: &[i64]) -> Self {
        let n = values.len();
        assert!(n > 0);
        let mut tree = Self {
            sum: vec![0; 4 * n],
            lazy: vec![0; 4 * n],
            n,
        };
        fn build(t: &mut LazySum, v: usize, left: usize, right: usize, a: &[i64]) {
            if right - left == 1 {
                t.sum[v] = a[left];
            } else {
                let mid = (left + right) / 2;
                build(t, v * 2, left, mid, a);
                build(t, v * 2 + 1, mid, right, a);
                t.sum[v] = t.sum[v * 2] + t.sum[v * 2 + 1];
            }
        }
        build(&mut tree, 1, 0, n, values);
        tree
    }
    fn apply(&mut self, v: usize, length: usize, delta: i64) {
        self.sum[v] += delta * length as i64;
        self.lazy[v] += delta;
    }
    fn push(&mut self, v: usize, left: usize, right: usize) {
        if right - left > 1 {
            let mid = (left + right) / 2;
            let d = self.lazy[v];
            self.apply(v * 2, mid - left, d);
            self.apply(v * 2 + 1, right - mid, d);
        }
        self.lazy[v] = 0;
    }
    fn update(&mut self, v: usize, left: usize, right: usize, from: usize, to: usize, delta: i64) {
        if to <= left || right <= from {
            return;
        }
        if from <= left && right <= to {
            self.apply(v, right - left, delta);
            return;
        }
        self.push(v, left, right);
        let mid = (left + right) / 2;
        self.update(v * 2, left, mid, from, to, delta);
        self.update(v * 2 + 1, mid, right, from, to, delta);
        self.sum[v] = self.sum[v * 2] + self.sum[v * 2 + 1];
    }
    fn query(&mut self, v: usize, left: usize, right: usize, from: usize, to: usize) -> i64 {
        if to <= left || right <= from {
            return 0;
        }
        if from <= left && right <= to {
            return self.sum[v];
        }
        self.push(v, left, right);
        let mid = (left + right) / 2;
        self.query(v * 2, left, mid, from, to) + self.query(v * 2 + 1, mid, right, from, to)
    }
    fn add(&mut self, left: usize, right: usize, delta: i64) {
        self.update(1, 0, self.n, left, right + 1, delta);
    }
    fn range_sum(&mut self, left: usize, right: usize) -> i64 {
        self.query(1, 0, self.n, left, right + 1)
    }
}
fn lazy_example(values: &[i64]) -> i64 {
    let mut tree = LazySum::new(values);
    tree.add(1, 4, 3);
    tree.range_sum(2, 5)
}

fn main() {
    let result = lazy_example(&[1, 2, 3, 4, 5, 6]).to_string();
    println!("{result}");
}

Complete std-only lazy-segment-tree program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Try it

Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.

What success looks like: You can justify the choice from constraints rather than from a remembered problem title.

Check your understanding

Trace Lazy Segment Tree on input values=[1,1,1,1,1,1]. Which result follows from the documented contract?

Reveal the answer
  1. 14
  2. 13
  3. 12

For this input the result is 13. An addition already included in this node's sum but not yet pushed to children. Compare this independent fixture with the worked trace: Add 3 to inclusive [1,4] of [1,2,3,4,5,6], giving [1,5,6,7,8,6]. Query [2,5] returns 27. A fully covered segment adds delta times segment length; partial descent pushes pending tags first.

Go deeper

Common misconception: “An update that must never affect the node sum”

An addition already included in this node's sum but not yet pushed to children. Add 3 to inclusive [1,4] of [1,2,3,4,5,6], giving [1,5,6,7,8,6]. Query [2,5] returns 27. A fully covered segment adds delta times segment length; partial descent pushes pending tags first.

  1. Concrete transition: Add 3 to inclusive [1,4] of [1,2,3,4,5,6], giving [1,5,6,7,8,6]. Query [2,5] returns 27. A fully covered segment adds delta times segment length; partial descent pushes pending tags first.
  2. Independent second fixture: Input values=[1,1,1,1,1,1] produces 13. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation.
  3. Boundary and contract: Input values=[2,4,6,8,10,12] produces 45. An addition already included in this node's sum but not yet pushed to children. The stated work bound is O(log n) update/query · O(n) space. Count actual state changes; a successful output test alone does not prove that bound.

Transfer challenge: Compare the visible input values=[1,2,3,4,5,6] with values=[9,8,7,6,5,4]. Predict why their results are 27 and 31. Then change one legal value and explain whether the same invariant, an addition already included in this node's sum but not yet pushed to children, still applies.

Connections

  • Lazy Segment Tree: Mental Model: Store pending range operations at covering nodes and push them only before descending.
  • Challenge: Lazy Segment Tree: Add 3 to inclusive indexes 1..4, then return the sum of inclusive indexes 2..5. Input contains at least six integers.
Reveal the Algorithm Atlas answer

27

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Lazy Segment Tree: When to Use It (courseId "algorithms", lessonId "algorithm.lazy-segment-tree.recognize")
Link: https://crabrix.com/learn/algorithms/algorithm.lazy-segment-tree.recognize
Goal: An addition already included in this node's sum but not yet pushed to children. State the input preconditions before applying this invariant.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.lazy-segment-tree.recognize) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.