Sub topic 9
Lazy propagation: range updates in O(log n)
This chapter assumes you can write the recursive segment tree from the earlier chapters, with build, point update and range query. It also assumes you are comfortable with recursion and O(log n) reasoning.
Why point updates are not enough
Suppose you must add v to every element in a[l..r], and also answer range sums. Using the point update from before costs O(n log n) per range add. That is too slow when the range is large.
Lazy propagation fixes this by postponing work. If an update fully covers a node's segment, you do not touch the children. You update that node's sum immediately and leave a note on the node. The note says: "every element below me still owes +v". The note is the lazy value. You hand it down to the children only when a later operation must look inside that node.
What each node stores
Each node keeps two values:
s[node]: the correct sum of its segment, including every update applied at or above this node.lz[node]: a pending add that the node's children have not yet received.
Applying v to a node whose segment has hi - lo + 1 elements raises the sum by v * (hi - lo + 1) and adds v to lz[node]. Pending adds combine by simple addition, so several updates can pile up on one node.
The code
class LazySegmentTree:
# Range add, range sum. Inclusive bounds, zero-indexed.
def __init__(self, a):
self.n = len(a)
self.s = [0] * (4 * self.n)
self.lz = [0] * (4 * self.n)
if self.n:
self._build(a, 1, 0, self.n - 1)
def _build(self, a, node, lo, hi):
if lo == hi:
self.s[node] = a[lo]
return
mid = (lo + hi) // 2
self._build(a, 2 * node, lo, mid)
self._build(a, 2 * node + 1, mid + 1, hi)
self.s[node] = self.s[2 * node] + self.s[2 * node + 1]
def _apply(self, node, lo, hi, v):
self.s[node] += v * (hi - lo + 1)
self.lz[node] += v
def _push(self, node, lo, hi):
if self.lz[node]:
mid = (lo + hi) // 2
self._apply(2 * node, lo, mid, self.lz[node])
self._apply(2 * node + 1, mid + 1, hi, self.lz[node])
self.lz[node] = 0
def add(self, l, r, v, node=1, lo=0, hi=None):
if hi is None:
hi = self.n - 1
if r < lo or hi < l:
return
if l <= lo and hi <= r:
self._apply(node, lo, hi, v)
return
self._push(node, lo, hi)
mid = (lo + hi) // 2
self.add(l, r, v, 2 * node, lo, mid)
self.add(l, r, v, 2 * node + 1, mid + 1, hi)
self.s[node] = self.s[2 * node] + self.s[2 * node + 1]
def query(self, l, r, node=1, lo=0, hi=None):
if hi is None:
hi = self.n - 1
if r < lo or hi < l:
return 0
if l <= lo and hi <= r:
return self.s[node]
self._push(node, lo, hi)
mid = (lo + hi) // 2
return (self.query(l, r, 2 * node, lo, mid)
+ self.query(l, r, 2 * node + 1, mid + 1, hi))
lt = LazySegmentTree([1, 2, 3, 4, 5])
lt.add(1, 3, 10)
print(lt.query(0, 4)) # 15 + 30 = 45
print(lt.query(2, 2)) # 13In add, a node falls into one of three cases. A node outside the range returns at once. A node fully inside gets _apply and stops. A node that only partly overlaps is pushed, then both children are visited, then its sum is rebuilt from them.
Why it stays O(log n)
At each level, at most two nodes partly overlap the range. Every other visited node either lies outside the range or is fully covered, and both cases stop at once. Each partial node does constant extra work, so an update visits O(log n) nodes. Queries follow the same pattern.
Common mistakes
- Skipping
_pushbefore descending. A child would then read a stale sum or receive a new update that is applied in the wrong order. - Forgetting to recompute
s[node]after recursing inadd. The parent would keep the old sum. - Applying
vwithout multiplying by the segment length. A sum needsv * length. - Reusing this pattern for other operations without redesign. Range assign, for example, cannot be stored as an add. It needs a "no pending value" marker, and it needs rules for combining a new assign with an old pending one.
Exercise
Start with LazySegmentTree([1, 2, 3, 4, 5]) and call add(0, 4, 1). What are s[1] and lz[1] afterward, and have the children of the root changed?
Show answer
The root segment [0, 4] is fully covered, so _apply runs on it and the update stops. s[1] becomes 15 + 1 * 5 = 20 and lz[1] becomes 1. The children are unchanged. They receive the pending 1 only when a later add or query needs to descend through the root.