Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Data Structures

Update Lazily.

Watch the explainer

A segment tree answers a range-sum query in O(log n) by combining a few precomputed nodes. But a range update — “add 10 to every element in [2, 5]” — would be O(n) if you dutifully walked down and changed every leaf. Lazy propagation is the trick that keeps updates O(log n) too: mark the handful of nodes that exactly cover the range with a pending lazy tag, update their aggregate, and defer pushing the change to their children until a later query actually descends through them. Do the range-add and watch just a few nodes get tagged instead of every leaf.

O(log n) range update & range query · lazy tag defers work · push down only when needed
segment tree

A binary tree over the array; each node stores an aggregate of its range.

covering nodes

The O(log n) nodes whose ranges exactly tile the query/update range.

lazy tag

A pending update stored on a node, not yet applied to its children.

push down

Apply a node’s lazy tag to its two children — done only when a query descends.

lazy.js — tag now, push down later
Ready
A segment tree over 8 values. Each node holds the sum of its range. A range +v update tags only the few nodes that exactly cover the range (a lazy value), instead of updating all the leaves. Range +v to try.
–
nodes tagged
–
leaves naive
–
last query

How it works

The idea is to be honest about a node’s aggregate immediately, but lazy about its descendants. When a range update fully covers a node, you can update that node’s stored sum right away — adding v × (size of its range) — because you know exactly how many elements it spans. What you postpone is telling its children. You stash v in the node’s lazy tag. Later, if a query or update needs to go below that node, you first “push down”: apply the tag to both children (updating their sums and their own lazy tags) and clear it. Because every update and query only ever visits O(log n) nodes and pushes down along one root-to-leaf path, both stay O(log n).

1

Find the covering nodes

For a range update, recurse from the root and stop at each node whose range lies entirely inside the update range. There are only O(log n) such nodes.

2

Update aggregate, defer the rest

At each covering node, add v × (its range size) to its stored sum immediately, and add v to its lazy tag — a promise to update its children later. Do not descend further.

3

Push down on demand

When a later operation needs to go below a tagged node, first push the tag to both children (updating their sums and lazy tags) and clear it. This keeps stored sums correct without ever touching untouched subtrees.

✓

Both operations stay O(log n)

Updates tag O(log n) covering nodes; queries combine O(log n) covering nodes, pushing down along one path. Range updates and range queries are both logarithmic.

Range update
O(log n)
Range query
O(log n)
Space
O(n)
Key trick
lazy tag

The code

# lazy propagation: range add, range sum def push_down(nd, l, r): if lazy[nd]: m = (l + r) // 2 for c, cl, cr in ((2*nd, l, m), (2*nd+1, m+1, r)): tree[c] += lazy[nd] * (cr - cl + 1) # apply to child sum lazy[c] += lazy[nd] # pass tag down lazy[nd] = 0 def update(nd, l, r, ql, qr, v): if qr < l or r < ql: return if ql <= l and r <= qr: # node fully covered tree[nd] += v * (r - l + 1); lazy[nd] += v # tag, don't descend return push_down(nd, l, r); m = (l + r) // 2 update(2*nd, l, m, ql, qr, v); update(2*nd+1, m+1, r, ql, qr, v) tree[nd] = tree[2*nd] + tree[2*nd+1]

Quick check

1. Why would a range update without lazy propagation be O(n)?

2. What does a lazy tag on a node represent?

3. When is a lazy tag pushed down to the children?

FAQ

What is a lazy segment tree?

A segment tree with lazy propagation, enabling range updates (e.g. add v to a whole range) in O(log n) instead of O(n). It stores a pending "lazy" tag on the O(log n) covering nodes — updating their aggregate now but deferring the push to children until an operation descends through them.

What is lazy propagation?

Deferring updates in a segment tree: apply a range update only to the few covering nodes and store a pending tag there, then push that tag down to a node’s children only when a later operation needs to look below it. Work is done lazily, on demand.

How does a lazy segment tree compare to a Fenwick tree?

A Fenwick tree is simpler and smaller, great for prefix sums with point (and, with a trick, range) updates, but hard to extend. A lazy segment tree is more general — range updates and queries for sum, min, max, assignment, etc. — at the cost of more code and memory. Fenwick for simple sums; lazy segment tree for flexible range ops.

What operations can lazy segment trees support?

Many range-update/range-query combos: range-add with range-sum, range-add with range-min/max, range-assign with range-sum/min/max, and more. The requirement is that lazy tags compose and can be applied to a node’s aggregate from its range size alone — making them a versatile tool for interval problems.

The picture: tags instead of writes

763046327tag +1031tag +101512345678 two tags, six nodes touched, four leaves left stale on purpose
The eight-element array [1, 2, 3, 4, 5, 6, 7, 8] after range_add(2, 5, +10). The two highlighted nodes covering [2..3] and [4..5] carry the new sums (27 and 31) and a pending tag of +10. The dashed leaves beneath them still hold 3, 4, 5, 6: they are out of date, and nothing needs them to be until an operation looks below the tags.

Worked example, step by step

Start with A = [1, 2, 3, 4, 5, 6, 7, 8] and a lazy tree over it (root sum 36). Run range_add(2, 5, +10), then ask range_sum(3, 6). Each row is one node visited, in the order the recursion reaches it; the last two columns show that node’s stored sum and lazy tag when it is visited (after any push).

OperationNode rangeWhat happensSumLazy
add(2,5,+10)[0..7]partial: recurse360
add(2,5,+10)[0..3]partial: recurse100
add(2,5,+10)[0..1]outside: skip30
add(2,5,+10)[2..3]covered: tag, stop2710
add(2,5,+10)[4..7]partial: recurse260
add(2,5,+10)[4..5]covered: tag, stop3110
add(2,5,+10)[6..7]outside: skip150
sum(3,6)[0..7]partial: recurse760
sum(3,6)[2..3]partial: push 10 down, recurse270
sum(3,6)[3..3]covered: read sum1410
sum(3,6)[4..5]covered: read sum3110
sum(3,6)[6..6]covered: read sum70

The update touched seven nodes and wrote only two tags; the array has six elements in range but none of them was visited. The query is where laziness pays its debt. Reaching [2..3] it is only partly inside the query, so it has to look at a child, and before doing so it pushes the +10 down: the children become 13 and 14 (they were 3 and 4) and the parent’s tag clears. Then [3..3] contributes 14. The node [4..5] lies fully inside the query, so its stored sum of 31 is read directly without ever pushing its tag; its stale leaves are never consulted. [6..6] adds 7. The answer is 14 + 31 + 7 = 52, which matches summing the updated array [1, 2, 13, 14, 15, 16, 7, 8] over indices 3 to 6 by hand.

Complexity and trade-offs

CaseTimeSpaceWhy
Lazy segment treeO(log n) update, O(log n) queryO(n)At most a constant number of nodes per level are partly covered, so the walk is about 4 log n nodes. Measured: with n = 1,024 a range add over indices 1 to 1,022 visited 39 nodes; with n = 16,384 it visited 55.
Plain arrayO(n) update, O(n) queryO(n)Every element in range is touched. The same 1,022-element add writes 1,022 cells. Fine for small n, and the right answer when updates are rare.
Prefix sumsO(n) update, O(1) queryO(n)Reads are instant but a range add must rewrite everything to its right.
Segment tree without lazyO(n log n) range update, O(log n) queryO(n)A range add becomes one point update per element in range.
Fenwick tree (two arrays)O(log n) bothO(n)Handles range add with range sum using two trees. Smaller and faster by a constant, but limited to sums.
Square-root blocksO(√n) bothO(n)Blocks of about √n with a tag each. Simpler to write, slower for large n.

Space is the hidden cost: each node needs a sum and a tag, and the array-backed layout needs room for a heap numbered from 1. For n = 6 the highest index used is 13, so a buffer of 2n is too small and 4n is the safe size. The real trade-off is generality. A lazy segment tree supports any aggregate whose tags compose (add with sum, add with min, assign with max), which a Fenwick tree cannot, at the price of more code and a bigger constant. Lazy propagation also needs the tag to be applicable from the range size alone: for sum that means v × length.

Common mistakes

  • Not pushing down before descending

    The tag is a promise to update the children, and descending without keeping it breaks the promise. On [1, 2, 3, 4], run add(0,1,5), sum(0,0): a version that skips the push returns 1 instead of 6, because the leaf for index 0 never received the +5. Push in both the update and the query, on every partly covered node, before recursing.

  • Adding v instead of v × length to the sum

    A covered node with r − l + 1 elements grows by v for each of them. On [1, 2, 3, 4], add(0,1,5) then sum(0,1) should be 13 but the version that adds only 5 to the node returns 8. The same slip appears in the push: the child’s length differs from the parent’s.

  • Overwriting the tag instead of accumulating it

    For range add, two updates on one node must add: tag = tag + v. Writing tag = v forgets the first. On [1, 2, 3, 4], add(0,1,5) twice then sum(0,0) returns 6 instead of 11. Assignment updates are a different operation and need their own rule for composing.

  • Forgetting to recompute the parent after recursing

    After the children are updated the partly covered node’s sum must be rebuilt as left + right. Skip it and the stored sum stays stale: add(0,0,5) then sum(0,1) on [1, 2, 3, 4] returns 3 instead of 8, since the node for [0..1] still says 3.

  • Allocating 2n slots

    The heap numbering from 1 with children at 2i and 2i+1 does not fill the array tightly unless n is a power of two. For n = 6 the highest index is 13, which is beyond a 12-slot buffer. Allocate 4n or size to the next power of two doubled.

Where this shows up

  • Range updates in contests and interviews

    Any problem phrased as “add to a whole interval, then ask for the sum, minimum or maximum of an interval” is a lazy segment tree, from temperature adjustments over a time range to “flip every light between l and r”.

  • Sweep-line geometry

    Computing the total area covered by a set of rectangles sweeps across x and keeps, for each y-interval, how many rectangles currently cover it. That structure is a segment tree whose range updates are applied to covering nodes, using the same idea of stopping early at fully covered nodes.

  • Counting and toggling over ranges

    Flipping a bit range and counting the ones, or assigning a value to a range and asking for its sum, are lazy trees with a different tag: toggle composes by xor, and assign replaces everything beneath.

  • Offline analytics over a timeline

    Applying a +1 to every day a campaign was active and then asking the busiest span is the same shape: many interval updates, followed by interval aggregates.

SOLVE IT YOURSELF

Solve it: update a whole range in O(log n)

A plain segment tree updates one element at a time — adding 5 to a million cells costs a million operations. Lazy propagation writes the update on a node and defers it until someone actually looks. Python or TypeScript.

YOUR TASK

Implement range_add(lo, hi, val) and range_sum(lo, hi) on a segment tree with lazy propagation. Both inclusive, both O(log n).

HINTS — 7 IDEAS
  1. Every node carries a lazy value: "everything below me still owes this much, and does not know it yet".
  2. Push before you read or descend: apply lazy × segment_length to this node’s sum, hand the value to both children, then clear it.
  3. Multiplying by the segment length is the step people miss — a pending +5 over 8 elements adds 40 to that node’s sum, not 5.
  4. On update: if the node’s range is fully inside the target, record the lazy value and push immediately, then return without touching any descendant. That early return is where the speed comes from.
  5. If it only partly overlaps, recurse into both children and recompute this node’s sum from theirs.
  6. On query, push before descending, or you read a sum that has not absorbed its pending update yet.
  7. Every node is either fully covered (stop) or partly (recurse), and only O(log n) nodes are ever partly covered.
CPython · WebAssembly

Keep going

▶  Watch it explained

Lazy Segment Tree: Time and Space Complexity, From First Principles

Finished this one? 0 / 99 Algorithms done
NextPersistent Segment Tree: Every Version Kept Next on the “Answering a range in log time” ladder · rung 5 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms