Learn / Advanced structures

Lazy propagation

Lazy propagation lets a segment tree update a whole range in O(log n). When an update covers a node's segment completely, apply it to that node and leave a note (the lazy tag) for its children; push the note down only when a later query or update needs to go below. The sheets this guide follows have no problems for this pattern, so the lesson explains the idea and when to use it.

How to recognise it

  • Range updates (add to every element in [l, r], or set them) mixed with range queries.
  • A plain segment tree would have to update every leaf in the range.
  • Updates that can be combined, like several additions in a row.

Tags

apply(k, len, v):  t[k] += v × len; lazy[k] += v
push(k):           if lazy[k]: apply to both children; lazy[k] = 0
update(k, lo, hi, l, r, v):
    if fully inside: apply(k, hi - lo + 1, v); return
    push(k); recurse into overlapping halves; recombine

Queries call push the same way before going down.

Common mistakes

  • Forgetting to push before recursing.
  • Combining 'set' and 'add' tags in the wrong order.

Problems

No problems listed for this pattern yet.

Check yourself

What does a lazy tag mean?

Adding v to a node covering 5 elements changes its sum by?

When is a tag pushed down?