Advanced Data Structures · 15 min · free lesson

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.

Core idea

An addition already included in this node's sum but not yet pushed to children. Add 3 to inclusive indexes 1..4, then return the sum of inclusive indexes 2..5. Input contains at least six integers.

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=[0,0,0,0,0,0]

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(&[0, 0, 0, 0, 0, 0]).to_string();
    println!("{result}");
}

Try your own version

Change the independent fixture `values=[0,0,0,0,0,0]` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `values=[1,2,3,4,5,6]`.

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 the lesson's own example.

Understand it

An addition already included in this node's sum but not yet pushed to children. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input values=[0,0,0,0,0,0], the worked program returns 9. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input values=[1,2,3,4,5,6]; predict that result before opening the answer reveal. The precise contract is: Add 3 to inclusive indexes 1..4, then return the sum of inclusive indexes 2..5. Input contains at least six integers.

Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

Solve the exact task, not just the visible example: Add 3 to inclusive indexes 1..4, then return the sum of inclusive indexes 2..5. Input contains at least six integers. On input values=[1,2,3,4,5,6], predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Store pending range operations at covering nodes and push them only before descending. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. An advanced structure or offline query order packages an invariant across operations. Name what each node, block, or reordered query state stores. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Check both correctness and cost. The intended bound is O(log n) update/query · O(n) space; explain which operation dominates it and how many times the input can trigger that operation. Test empty ranges, repeated updates, undo operations where supported, and the exact boundary between adjacent blocks. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.

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(&[0, 0, 0, 0, 0, 0]).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.

Practice starter

pub fn solve(input: &str) -> String {
    // Add 3 to inclusive indexes 1..4, then return the sum of inclusive indexes 2..5. Input contains at least six integers.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement lazy-segment-tree")
}

Try it

Add 3 to inclusive indexes 1..4, then return the sum of inclusive indexes 2..5. Input contains at least six integers.

What success looks like: The private harness prints PASS lazy-segment-tree. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.

Check your understanding

Boundary check for lazy-segment-tree: with input values=[2,4,6,8,10,12], what result should solve return?

Reveal the answer
  1. 45
  2. 46
  3. 44

For this input the result is 45. 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. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: An addition already included in this node's sum but not yet pushed to children. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses values=[0,0,0,0,0,0] and computes 9. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For values=[2,4,6,8,10,12], the independently calculated result is 45. The complexity discussion uses O(log n) update/query · O(n) space. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture values=[0,0,0,0,0,0] in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge values=[1,2,3,4,5,6].

Connections

  • Lazy Segment Tree: When to Use It: range updates plus range aggregate queries
  • Randomized Treap: Mental Model: Keep BST order by key and heap order by random priority; insertion rotates a new node up and deletion merges its children.
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: Challenge: Lazy Segment Tree (courseId "algorithms", lessonId "algorithm.lazy-segment-tree.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.lazy-segment-tree.challenge
Goal: An addition already included in this node's sum but not yet pushed to children. Add 3 to inclusive indexes 1..4, then return the sum of inclusive indexes 2..5. Input contains at least six integers.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.lazy-segment-tree.challenge) 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.