Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Lazy Propagation

Range updates by deferring work: composing tags, and segment tree beats.

Add 5 to every element of a[l..r]a[l..r]: a plain segment tree must touch every leaf in the range, O(n)O(n) work. Lazy propagation writes the update on the O(log⁡n)O(\log n) nodes that cover the range and leaves a note on each, a tag, to be handed down only when someone looks inside. Range assignment, affine maps and bit flips all work the same way once the tags obey a small algebra, and a potential argument even handles "replace every a[i]a[i] by min⁡(a[i],x)\min(a[i], x)", which no tag can describe.

What you’ll learn

  • Implement range updates with lazy tags: apply them to covered nodes, push them down before visiting children, and prove O(log⁡n)O(\log n) worst-case time per operation with an invariant.
  • State the algebra behind every lazy segment tree, a monoid of tags acting on a monoid of values by homomorphisms, and build the tags for add, assign, affine maps and flips.
  • Compose tags in the right order, including assignments mixed with additions, and keep the range lengths that sums need.
  • Explain segment tree beats (Ji, 2016): range chmin with range sums in O((n+q)log⁡n)O((n+q)\log n) total time, through a potential that counts distinct values.

Tags: deferring work

Take range add with range sum. An update a[l..r]+=xa[l..r] \mathrel{+}= x follows the same path as a query on [l,r][l, r] and reaches the O(log⁡n)O(\log n) nodes that such a query would take whole. At each of them it does two O(1)O(1) things and stops: it adds x⋅len(v)x\cdot\mathrm{len}(v) to the stored sum, which is now correct, and it adds xx to the node's tag, a promise that every element below still owes xx.

Before any later operation enters the children of a tagged node, it pushes the tag: it applies the tag to both children, adds it to their own tags, and clears it. This is lazy propagation: work is deferred until someone needs its result.

python
class LazySum:                                   # range add, range sum; s and tag have 4n slots
    # __init__ builds s like a plain segment tree and sets every tag to 0

    def _apply(self, v, l, r, x):                # add x to all of node v's range, in O(1)
        self.s[v] += x * (r - l + 1)
        self.tag[v] += x                         # the children still owe x

    def _push(self, v, l, r):                    # hand the pending tag to both children
        if self.tag[v]:
            m = (l + r) // 2
            self._apply(2 * v, l, m, self.tag[v])
            self._apply(2 * v + 1, m + 1, r, self.tag[v])
            self.tag[v] = 0

    def add(self, ql, qr, x, v=1, l=0, r=None):  # a[ql..qr] += x: O(log n)
        if r is None: r = self.n - 1
        if qr < l or r < ql: return
        if ql <= l and r <= qr:
            self._apply(v, l, r, x); return      # covered: tag it and stop here
        self._push(v, l, r)                      # partial: push, recurse, recompute
        m = (l + r) // 2
        self.add(ql, qr, x, 2 * v, l, m); self.add(ql, qr, x, 2 * v + 1, m + 1, r)
        self.s[v] = self.s[2 * v] + self.s[2 * v + 1]

    def query(self, ql, qr, v=1, l=0, r=None):   # sum of a[ql..qr]: O(log n)
        if r is None: r = self.n - 1
        if qr < l or r < ql: return 0
        if ql <= l and r <= qr: return self.s[v]
        self._push(v, l, r)                      # look inside only after pushing
        m = (l + r) // 2
        return self.query(ql, qr, 2 * v, l, m) + self.query(ql, qr, 2 * v + 1, m + 1, r)

Leaves get tags too here, harmlessly, since no one ever pushes from a leaf. A point update would push along its root-to-leaf path in the same way.

Check your understanding

Right after the range add +2 on [1,5][1, 5], with tags waiting on nodes 5 ([2,3][2, 3]) and 6 ([4,5][4, 5]), which of these queries pushes no tag down?

  1. [3,3][3, 3]
  2. [2,2][2, 2]
  3. [1,5][1, 5]
  4. [4,4][4, 4]
Show the answer

C. [1,5][1, 5]

Query [1,5][1, 5] takes nodes 5 and 6 whole, and their stored sums already include the +2, so it never needs their children. The other three queries must enter node 5 or node 6, and push its tag first.

The algebra of tags

Sums need care. After "add xx", a node's sum becomes s+xℓs + x\ell, which depends on its length ℓ\ell and not on ss alone. So store pairs (s,ℓ)(s, \ell), combined by (s1,ℓ1)⋅(s2,ℓ2)=(s1+s2, ℓ1+ℓ2)(s_1, \ell_1)\cdot(s_2, \ell_2) = (s_1 + s_2,\ \ell_1 + \ell_2); every update in the table below is then a homomorphism of pairs.

UpdateQueryStored valueTag applied to a nodeFirst gg, then ff
add xxsum(s,ℓ)(s, \ell)(s+xℓ, ℓ)(s + x\ell,\ \ell)add xg+xfx_g + x_f
add xxminimummmm+xm + xadd xg+xfx_g + x_f
assign ccsum(s,ℓ)(s, \ell)(cℓ, ℓ)(c\ell,\ \ell)assign cfc_f: the newer wins
assign ccminimummmccassign cfc_f
affine y↦αy+βy \mapsto \alpha y + \betasum(s,ℓ)(s, \ell)(αs+βℓ, ℓ)(\alpha s + \beta\ell,\ \ell)(αfαg, αfβg+βf)(\alpha_f\alpha_g,\ \alpha_f\beta_g + \beta_f)
flip every bitcount of 1s(o,ℓ)(o, \ell)(ℓ−o, ℓ)(\ell - o,\ \ell)two flips cancel
Additions and assignments together are affine maps: add xx is (1,x)(1, x) and assign cc is (0,c)(0, c). The AtCoder Library's lazy_segtree takes exactly these ingredients as parameters: the value type with its operation and identity, the tag type, the action, the composition and the identity tag.
DerivationAffine tags act by homomorphisms and compose
  1. f((s1,ℓ1)⋅(s2,ℓ2))=(α(s1+s2)+β(ℓ1+ℓ2), ℓ1+ℓ2)=f(s1,ℓ1)⋅f(s2,ℓ2)f\big((s_1, \ell_1)\cdot(s_2, \ell_2)\big) = \big(\alpha(s_1 + s_2) + \beta(\ell_1 + \ell_2),\ \ell_1 + \ell_2\big) = f(s_1, \ell_1)\cdot f(s_2, \ell_2)

    Applying f=(α,β)f = (\alpha, \beta) to a combined node gives the same result as applying it to each half and combining:

  2. αf(αgy+βg)+βf=(αfαg) y+(αfβg+βf)\alpha_f(\alpha_g y + \beta_g) + \beta_f = (\alpha_f\alpha_g)\,y + (\alpha_f\beta_g + \beta_f)

    First g=(αg,βg)g = (\alpha_g, \beta_g), then ff: every element yy becomes

  3. tag[c]←tag[v]∘tag[c],val[c]←tag[v](val[c])\mathrm{tag}[c] \leftarrow \mathrm{tag}[v] \circ \mathrm{tag}[c], \qquad \mathrm{val}[c] \leftarrow \mathrm{tag}[v]\big(\mathrm{val}[c]\big)

    Composition is not commutative, so a push must put the parent's tag after the child's: the parent's tag arrived later than anything already pushed to the child.

Check your understanding

A node holds the pending tag "assign 3", and then receives the update "add 2". Which single tag represents both?

  1. add 5
  2. assign 3
  3. assign 5
  4. None: an assignment and an addition cannot be merged
Show the answer

C. assign 5

As affine maps, add 2 after assign 3 is (1,2)∘(0,3)=(0, 1⋅3+2)=(0,5)(1, 2)\circ(0, 3) = (0,\ 1\cdot3 + 2) = (0, 5): assign 5. In the opposite order, add 2 first and then assign 3, the result would be assign 3.

Correctness, and the O(log n) bound

DerivationProof
  1. true(v)=(troot∘⋯∘tparent(v))(val[v])\text{true}(v) = \big(t_{\mathrm{root}} \circ \cdots \circ t_{\mathrm{parent}(v)}\big)\big(\mathrm{val}[v]\big)

    Invariant. Every update that has not yet reached node vv waits in the tags of vv's proper ancestors, and deeper tags are older, since any later update passing an ancestor would have pushed that ancestor's tag first. So the true aggregate of vv's range is its stored value with the pending ancestor tags applied, nearest first:

  2. val[c]←t(val[c]),tag[c]←t∘tag[c],tag[v]←id\mathrm{val}[c] \leftarrow t\big(\mathrm{val}[c]\big), \qquad \mathrm{tag}[c] \leftarrow t \circ \mathrm{tag}[c], \qquad \mathrm{tag}[v] \leftarrow \mathrm{id}

    Pushing preserves it. A push applies vv's tag tt to each child's value, composes it after the child's own tag, and resets vv's tag to the identity: the same equation now holds with tt one level lower.

  3. val[v]←val[2v]⋅val[2v+1]\mathrm{val}[v] \leftarrow \mathrm{val}[2v]\cdot\mathrm{val}[2v+1]

    Reading and writing. Every operation walks down from the root and pushes at each node it splits, so every node it reads has no pending tag above it, and its stored value is exact. A node taken whole by an update absorbs it in O(1)O(1) thanks to the homomorphism, and each split node is recomputed from its children on the way back up:

  4. T(n)=O(⌈log⁡2n⌉+1)=O(log⁡n)T(n) = O(\lceil\log_2 n\rceil + 1) = O(\log n)

    Cost. An update visits exactly the nodes a query on the same range visits, at most 4 per level, and it pushes only at split nodes, at most 2 per level, each push costing two applications and two compositions. So every operation does O(1)O(1) work per level:

Predict before you look

With n=8n = 8, a lazy range add on a[1..6]a[1..6] visits how many nodes, counting the ones it skips?

Show the answer

11 nodes

Exactly the nodes a query on [1,6][1, 6] visits, the worst case for n=8n = 8: nodes 1, 2, 4, 8 (skipped), 9, 5, 3, 6, 7, 14 and 15 (skipped). The update changes the 4 nodes taken whole (leaves 9 and 14 in place, nodes 5 and 6 with a tag) and recomputes the 5 split nodes on the way back up.

Beyond tags: segment tree beats

Some updates have no tag. Range chmin replaces each a[i]a[i] with l≤i≤rl \le i \le r by min⁡(a[i],x)\min(a[i], x), and with sums stored, the new sum depends on how many elements exceed xx and by how much. Ji Ruyi's segment tree beats (2016) stores more in each node, the maximum M1M_1, the strict second maximum M2M_2, the number cc of elements equal to M1M_1, and the sum, and distinguishes three cases at a node inside the range:

  • Break, M1≤xM_1 \le x: nothing changes; return.
  • Tag, M2<x<M1M_2 < x < M_1: only the cc maximal elements change, so the sum drops by c (M1−x)c\,(M_1 - x) and M1M_1 becomes xx; the children learn the new cap at the next push; return.
  • Beat, x≤M2x \le M_2: at least two distinct values change; push and recurse into both children.
python
# per node: mx (maximum), se (strict second maximum), cnt (copies of mx), sm (sum)
def _cap(self, v, x):                      # lower node v's maximum to x; needs se[v] < x
    if self.mx[v] > x:
        self.sm[v] -= (self.mx[v] - x) * self.cnt[v]
        self.mx[v] = x

def _push(self, v):                        # a child may not exceed its parent's maximum
    self._cap(2 * v, self.mx[v]); self._cap(2 * v + 1, self.mx[v])

def chmin(self, ql, qr, x, v=1, l=0, r=None):
    if r is None: r = self.n - 1
    if qr < l or r < ql or self.mx[v] <= x:
        return                             # break: nothing in this node changes
    if ql <= l and r <= qr and self.se[v] < x:
        self._cap(v, x); return            # tag: only the maximal elements change
    self._push(v)                          # beat: recurse into both children
    m = (l + r) // 2
    self.chmin(ql, qr, x, 2 * v, l, m); self.chmin(ql, qr, x, 2 * v + 1, m + 1, r)
    self._pull(v)                          # recompute mx, se, cnt and sm from the children

The node's maximum doubles as its tag: _push caps each child at the parent's maximum, which is valid because a child's second maximum is always below it. _pull merges the children's maxima, counts and second maxima in O(1)O(1); range sum queries are the usual ones, with pushes.

DerivationProof: count distinct values
  1. Φ0 ≤ ∑vlen(v) = O(nlog⁡n)\Phi_0\ \le\ \sum_v \mathrm{len}(v)\ =\ O(n\log n)

    Let Φ\Phi be the sum over all nodes of the number of distinct values in the node's range. Each level contributes at most nn:

  2. each beat visit:ΔΦ ≤ −1\text{each beat visit:}\quad \Delta\Phi\ \le\ -1

    At a beat node, x≤M2<M1x \le M_2 < M_1, so after the update M1M_1, M2M_2 and every value between them have merged into the single value xx: the node loses at least one distinct value. Every node a beat recurses into either stops at once, as an ordinary visit, or is itself a beat node.

  3. per update:ΔΦ ≤ O(log⁡n)\text{per update:}\quad \Delta\Phi\ \le\ O(\log n)

    A node fully inside the range never gains a distinct value: the values above xx become xx, and in the tag case xx replaces exactly one value. Only the O(log⁡n)O(\log n) split nodes, where elements outside the range keep their old values, can gain one value each, namely xx:

  4. Ttotal = O(qlog⁡n)+O(nlog⁡n+qlog⁡n) = O((n+q)log⁡n)T_{\text{total}}\ =\ O(q\log n) + O(n\log n + q\log n)\ =\ O\big((n + q)\log n\big)

    The ordinary visits cost O(log⁡n)O(\log n) per operation, and each extra visit is paid for by a unit of Φ\Phi, which starts at O(nlog⁡n)O(n\log n) and grows by O(log⁡n)O(\log n) per update:

Mixing in range additions breaks this potential, because an addition over part of a node can split equal values apart again; for that case Ji proved O((n+q)log⁡2n)O((n+q)\log^2 n) total time. The same work treats historic queries, such as the largest value an element has ever held.

Check your understanding

A segment-tree-beats node lies inside the range of a chmin with x=8x = 8. Its maximum is 10, held by 2 elements, its strict second maximum is 7, and its sum is 30. What happens at this node?

  1. Break: nothing changes
  2. Tag: both 10s become 8, the sum becomes 26, and the recursion stops here
  3. Beat: recurse into both children
  4. Every element of the node becomes 8
Show the answer

B. Tag: both 10s become 8, the sum becomes 26, and the recursion stops here

M2=7<x=8<M1=10M_2 = 7 < x = 8 < M_1 = 10, the tag case: only the elements equal to 10 change, so the sum drops by 2⋅(10−8)=42\cdot(10 - 8) = 4 to 26 and the maximum becomes 8. For the array [10,7,10,3][10, 7, 10, 3] this happens at the root, after a single visit.

Key takeaways

  • A lazy update applies itself in O(1)O(1) to the O(log⁡n)O(\log n) nodes that cover its range and leaves a tag there; any operation that later enters a tagged node's children pushes the tag down first.
  • The general rule: values form a monoid, tags form a monoid of maps that act on values by homomorphisms; then tags apply to whole nodes and compose in O(1)O(1). Sums need the range length stored alongside.
  • Assignments and additions are affine maps (α,β)(\alpha, \beta) and compose as (αfαg, αfβg+βf)(\alpha_f\alpha_g,\ \alpha_f\beta_g + \beta_f), newer tag outside: the order matters.
  • Pending tags above a node are its only missing updates, and operations push before looking inside, so every operation is correct and costs O(log⁡n)O(\log n) in the worst case.
  • Updates with no tag, such as range chmin with sums, can still be fast: segment tree beats recurses only where a node loses a distinct value, O((n+q)log⁡n)O((n+q)\log n) in total (Ji, 2016).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

When must a lazy segment tree push a node's tag down to its children?

  1. Immediately after the tag is created
  2. Only when the node is a leaf
  3. Before any operation enters the node's children, by splitting the node or walking through it
  4. Once every n\sqrt n operations, in a batch
Show the answer

C. Before any operation enters the node's children, by splitting the node or walking through it

A tagged node's own stored value is already correct; only its children are out of date. The children matter only when an operation looks inside, so that is the moment to push. Pushing at creation would make every range update O(n)O(n) again.

Question 2

A node holds the pending tag y↦2y+1y \mapsto 2y + 1, and then receives the update y↦3y+4y \mapsto 3y + 4. What is the combined tag?

  1. y↦6y+9y \mapsto 6y + 9
  2. y↦6y+7y \mapsto 6y + 7
  3. y↦5y+5y \mapsto 5y + 5
  4. y↦6y+4y \mapsto 6y + 4
Show the answer

B. y↦6y+7y \mapsto 6y + 7

The older map acts first: 3(2y+1)+4=6y+73(2y + 1) + 4 = 6y + 7. In pair form, (3,4)∘(2,1)=(3⋅2, 3⋅1+4)=(6,7)(3, 4)\circ(2, 1) = (3\cdot2,\ 3\cdot1 + 4) = (6, 7).

Question 3

Why can't a tag on (sum,length)(\text{sum}, \text{length}) pairs implement "range chmin", a[i]←min⁡(a[i],x)a[i] \leftarrow \min(a[i], x), with range sums?

  1. The new sum depends on how many elements exceed xx and by how much, which the sum and length do not determine
  2. Minimum is not associative
  3. Two chmin updates cannot be composed
  4. The length of a node is not known during an update
Show the answer

A. The new sum depends on how many elements exceed xx and by how much, which the sum and length do not determine

Two nodes can have the same (s,ℓ)(s, \ell) yet different sums after a chmin, so the update is not a function of the stored value at all. Segment tree beats stores more, the maximum, the second maximum and the maximum's count, and recurses when that is not enough.

Further reading

  • A. Laaksonen, Competitive Programmer's Handbook (2018), chapter 28.
  • CP-Algorithms, Segment Tree, section on range updates (lazy propagation).
  • M. Pătraşcu & E. D. Demaine, "Tight bounds for the partial-sums problem," Proceedings of the 15th ACM-SIAM Symposium on Discrete Algorithms (SODA) (2004), 20–29.