# Lazy Propagation in Segment Tree in Java

The topic lazy propagation in segment tree in Java is the continuation of the topic segment tree in Java. Readers are advised to go through the segment tree topic first. Lazy propagation in a segment tree means postponing the updates of some values and updating them only when it is required.

## Update Operation

Let's recall the update operation of a segment tree.

1. Begin with the root of the segment tree.
2. If the range of the current node does not contain the index of the input array, then return.
3. Else update the current node and repeat from step 2 for the children of the current node. ## Scenario for Lazy Propagation

Let's discuss a scenario where one should use the lazy propagation technique.

Suppose the task is to add the value 6 to each of the elements of the input array from the index 1 to 4. To do the task, one has to call the update() method for each element from index 1 to 4. These multiple calls lead to more time consumption. It is where the lazy propagation technique kicks in to make the update process fast.

Note that a node of the segment tree contains the result of a query for a range of indices. And if the range of this node lies within the range of the update operation, then all the descendants of that node have to be updated. For example, if we consider the node with the value 35 in the above diagram, then the node contains the sum of values at the indices from 3 to 5 (see the above diagram). If the query of an update is for the range 2 to 5, then we have to update that node and all the descendants of that node. Using the lazy propagation, we need to update the node with value 35 and defer the updates of its descendants by containing this information of update in the separate nodes known as lazy nodes or the values. We create an array lazy[] that represents the lazy nodes. The size of the array lazy[] is the same as the array that does the representation of the segment tree, which is t[] in the following code.

The approach is to initialize all the elements of the array lazy[] as 0. A value of 0 in the array lazy[j] shows that there are no updates pending on node j in the segment tree. Any other value (let's say the value is v) of lazy[j] means that tree before making any query to the node, v amount must be added to the node j in the segment tree.

## Implementation of Lazy Propagation

Observe the following program.

FileName: LazySegTree.java

Output:

```The sum of the values in the given range is: 33
The sum of the values, after updation, in the given range is: 61
```

## Help Others, Please Share   