Lazy propagation: updating a whole range at once
1 Adds to whole ranges, mixed with range sums
The segment tree from the last lesson answers a range sum in O(log n) and changes one value in O(log n). Some problems change a whole range at once. They mix two kinds of operation:
- Add: add v to every value from index l to index r.
- Sum: return the sum of the values from index l to index r.
There can be 10⁵ operations on an array of 10⁵ values, and each sum must see every add made before it. The tools so far each fail at one part:
- A plain array. An add or a sum loops over up to n values. That is around 10¹⁰ steps in all, so it gets Time Limit Exceeded (TLE).
- A segment tree with point updates. One add becomes one point update per index, up to n updates of log n steps each. That is around 10¹¹ steps, worse than the plain array.
- A difference array. An add takes two steps, but the values exist only after the final walk. Each sum in between needs a fresh walk of n steps.
Lazy propagation makes both operations O(log n). It is a segment tree that does not pass an add down to the values until it has to.
2 A note on the boss's desk
In the segment tree lesson, each node is a boss who knows the total of their whole team. Node 4-7 knows the sum of indexes 4 to 7.
Now head office announces a raise: everyone from index 2 to index 7 gets 2 more. The boss of 4-7 sees that her whole team is inside the range. She does not walk to each desk. She does two things:
- She adds 2 × 4 = 8 to her team's total, because four people each got 2. Her total is right again at once.
- She writes a sticky note, "+2 each", and keeps it on her desk. Her two reports have not heard about the raise yet.
The note stays on her desk until someone asks about a smaller part of her team, such as indexes 4 and 5. Before she passes that question down, she hands the note to both reports. Each report adds 2 times the size of their own team to their total, and keeps the note for their own team. Then she throws her note away.
In code, the notes are a second array, lazy, with one place per node. A node takes an add with two lines:
tree[node] = tree[node] + v × length
lazy[node] = lazy[node] + v
Here length is the number of values in the node's range. A node's sum is always right. Its note says what its children have not been told yet.
Our running example is nums = [2, 5, 5, 1, 3, 5, 3, 7]. The first tree below shows each node's range, and the second shows its sum in the same place. We draw the top three levels. The leaves, one per value, hang below 0-1 to 6-7.
3 Passing the note down
Handing the note to the two reports is the push down. Before any function goes below a node, it pushes that node's note to both children:
- Each child takes the note as an add. Its sum grows by the note times its own length, and its own note grows by the note.
- The node's note goes back to 0.
The sum and the add both push. A sum that goes below a node needs the children's sums to be right. An add that goes below a node rebuilds that node's sum from its children at the end, so the children must hold the old note by then.
An add follows the same three cases as a sum:
- Outside the range: do nothing.
- Wholly inside: take the add at this node, and stop.
- Cut by the range: push down, go into both children, then pull up. Pulling up sets the node's sum to its two children's sums added together.
A note goes no further than the questions need. Only the nodes below a note are behind, and nothing reads them without passing that note first.
4 One add and one sum, traced
We add 2 to indexes 2 to 7, and then ask for the sum of indexes 4 and 5. The drawings show each node's sum, in the same places as the trees above. A note comes after the sum, so 26+2 means the sum is 26 and the node holds a +2 note for its children. Blue marks the nodes each step works on.
The add, call by call:
| Call | Node | Case | What happens | Sum | Note |
|---|---|---|---|---|---|
| 1 | 0-7 | cut | push (no note), go down | 31 | 0 |
| 2 | 0-3 | cut | push (no note), go down | 13 | 0 |
| 3 | 0-1 | outside | stop | 7 | 0 |
| 4 | 2-3 | inside | 6 + 2 × 2 | 10 | +2 |
| 5 | 0-3 | cut | pull up: 7 + 10 | 17 | 0 |
| 6 | 4-7 | inside | 18 + 2 × 4 | 26 | +2 |
| 7 | 0-7 | cut | pull up: 17 + 26 | 43 | 0 |
The sum of [4, 5]:
| Node | Case | What happens | Returns |
|---|---|---|---|
| 0-7 | cut | push (no note), go down | 0 + 12 = 12 |
| 0-3 | outside | stop | 0 |
| 4-7 | cut | push +2: 4-5 becomes 12, 6-7 becomes 14 | 12 + 0 = 12 |
| 4-5 | inside | stop | 12 |
| 6-7 | outside | stop | 0 |
The add changed six values but visited only five nodes, and it left notes on two of them. The sum moved one note down one level. The note on 2-3 is still waiting. Leaves 2 and 3 still hold 5 and 1, but 2-3's sum of 10 is right, and that is all a question about indexes 2 and 3 reads.
5 The code
The class adds lazy, apply and pushDown to the segment tree from the last lesson. queryNode keeps its three cases and calls pushDown before it goes lower. updateNode now takes a range, and it stops at every node wholly inside it.
On our example, rangeAdd(2, 7, 2) and then rangeSum(4, 5) returns 12, and rangeSum(0, 7) returns 43.
6 Why it stays O(log n)
An add visits the same nodes as a sum over the same range. At each level, only two nodes can be cut by the range: the one holding its left end and the one holding its right end. Every other node on that level is wholly inside or wholly outside, so it stops at once.
Only cut nodes go lower, so each level sees at most four nodes. At n = 10⁵ the tree has about 17 levels, so one operation visits fewer than 70 nodes. A push is two calls to apply, which is O(1).
So each add and each sum is O(log n). With the O(n) build, q operations take O(n + q log n). At n = q = 10⁵, that is a few million steps.
tree and lazy each take 4n places, so the extra space is O(n).
7 Mistakes
Each input below starts from our example after the add of 2 to [2, 7].
- No push in the sum. 4-5 never gets the +2, so the sum of [4, 5] comes out 8 instead of 12.
- No push in the add. Add 1 to [4, 5]. 4-7 pulls up from children that never got its +2, so the sum of [4, 7] comes out 20 instead of 28.
- The wrong length. Each child takes the note times its own length,
mid - start + 1orend - mid. With the parent's length of 4, the sum of [4, 5] comes out 16 instead of 12. Halving the parent's length fails too, because 0-4 splits into 0-2 and 3-4. - Not clearing the note. Ask for the sum of [4, 5] twice. The second push hands the same +2 down again, so the answers are 12 and then 16.
- A tree array of 2n. It is too small when n is not a power of two. With n = 6 the tree uses node 13. An array of 4n places is always enough.
- Overflow. With 10⁵ values near 10⁹, a sum reaches 10¹⁴. So
tree,lazyandv × lengthuselong long.
8 Other notes, and when to use it
The note changes with the operation. Three changes come up in this pattern's problems:
- Set instead of add. A set wipes out what came before. So a new note replaces the old one instead of adding to it, and the node's sum becomes v × length. Setting to 0 is a real note, so "no note" needs its own marker, such as a separate true or false array. When a problem has both, a set at a node also throws away that node's add note.
- Minimum or maximum with range add. Adding v to every value raises the maximum by v, not by v × length. So
applyadds just v to the node's value. - Indexes up to 10⁹. Bookings over times up to 10⁹ cannot get an array of 4 × 10⁹. Rank the times first, as in the coordinate compression lesson, or create each node only when an operation first reaches it.
The sign for lazy propagation is a whole range changing at once, with questions about ranges mixed in:
| Changes | Questions | Use |
|---|---|---|
| Whole ranges, all before any question | The final values | Difference array |
| One value at a time | Range sums | Fenwick tree or segment tree |
| Whole ranges, mixed with questions | Range sums, minimums or maximums | Lazy propagation |
pushDown first. When an answer comes out wrong, check that before anything else.This is the last lesson on the roadmap.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.