Explain the concept of 'Lazy Propagation' in Segment Trees.
Instruction: Discuss how 'Lazy Propagation' improves the efficiency of Segment Trees during updates.
Updated
Official answer
Lazy propagation defers updating descendants while keeping each queried node's aggregate correct. For a range-add/range-sum tree, a fully covered node representing length L is updated immediately: sum increases by delta·L and its pending-add tag increases by delta. Descendants can wait.
Before descending for a partially overlapping query or update, push the tag to the children: update each child's aggregate using its own length and compose the child's tag. Clear the parent tag, process the needed children, and recompute the parent's aggregate when required. Returning a fully covered node must already return its updated sum.
For [1,2,3,4], adding 5 to all four entries changes the total from 10 to 30 without visiting every leaf. A later query of the first two entries must return 13. Overlapping updates must compose correctly.
The update operation must be compatible with the stored aggregate and have constant-size composable tags. Assignment then addition is different from addition then assignment; a single additive tag cannot represent both. Standard compatible range updates and queries can be O(log n), with O(n) storage. This is a specific algebraic contract, not an automatic speedup for every possible range operation.