×

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic. In a segment tree, lazy propagation means delaying the updating of certain values and changing them just when necessary.

Update operation

Let's think back to how a segment tree is updated.

  • Start at the segment tree's base.
  • Return if the current node's range does not include the input array's index.
  • If not, update the current node and proceed to step 2 again for the current node's children.

The Lazy Propagation Scenario

Let's talk about a situation when the lazy propagation strategy would be appropriate.

Assume that the assignment is to add the number 6 to each of the input array's items from index 1 to 4. The update() method must be called for each item from index 1 to 4 to complete the operation. More time is spent as a result of these numerous calls. Here is where the update process becomes quick thanks to the lazy propagation strategy.

Be aware that the outcome of a search for just several indices is contained in a node of a segment tree. Furthermore, all of that node's descendants must be updated if the update operation's range overlaps with this node's range. In the picture above, for instance, the node with value 35 includes the total of elements at the indexes from 3 to 5. (See the above diagram). Modify that node and all of its descendants if the update's query falls within the range of 2 to 5.

We must upgrade the node with the number 35 via lazy propagation and postpone the changes of its successors by storing the updated information in different nodes known as sleepy nodes or values. To represent the lazy nodes, we make an array called lazy[]. The size of the array t[] in the following code is the same as that

of the array lazy[], which represents the segment tree.

The strategy is to initialize each element of the lazy[] array as 0. The segment tree node j has no changes pending, as shown by a value of 0 in the array lazy[j]. Any alternative value for lazy[j] (let's say it is v) signifies that the segment tree's node j must first be added to by an amount equal to v before any queries can be made.

How to Update a Node in a Segment Tree Using Lazy Propagation

//To reflect updates in the array elements in the segment tree

// Between x and y in the array.

updateRange (us, ue)

1) If there are any pending updates for any nodes in the current segment tree, then

complete that node's pending change first.

2) If the current node's range is entirely within the update query's range, update the current node first. Then, update any child nodes by setting their lazy values to true.

3) Use the same procedure as the last simple update if the current node's range overlaps the update range:

  1. Recur for the left and right children.
  2. Update the current node with the outcomes of the left and right calls.

The use of lazy propagation

LSTE1.java

public class LSTE1
{  
final int MAX_SIZE = 50;    
int s[] = new int[MAX_SIZE]; 
int l[] = new int[MAX_SIZE];
void updateRangeUtil(int currNode, int y, int z, int t, int f, int v)  
{
if (l[currNode] != 0)  
{ 
s[currNode] += (z - y + 1) * l[currNode];  
if (y != z)  
{  
l[2 * currNode + 1] += l[currNode];  
l[2 * currNode + 2] += l[currNode];  
}  
l[currNode] = 0;  
}
if (y > z || y > f || z < t)  
{  
return;  
}  
if (y >= t && z <= f)  
{ 
s[currNode] += (z - y + 1) * v; 
if (y != z)  
{  
l[2 * currNode + 1] += v;  
l[2 * currNode + 2] += v;  
}  
return;  
}  
int m = (y + z) / 2;  
updateRangeUtil(2 * currNode + 1, y, m, t, f, v);  
updateRangeUtil(2 * currNode + 2, m + 1, z, t, f, v);  
s[currNode] = s[2 * currNode + 1] + s[2 * currNode + 2];  
} 
void updateRange(int n, int y, int z, int v)   
{  
updateRangeUtil(0, 0, n - 1, y, z, v);  
}  
int getSumUtil(int y, int z, int t, int f, int si)  
{  
if (l[si] != 0)  
{  
s[si] += (z - y + 1) * l[si];  
if (y != z)  
{
l[2 * si + 1] += l[si];  
l[2 * si + 2] += l[si];  
}  
l[si] = 0;  
} 
if (y > z || y > f || z < t)  
{  
return 0;  
}  
if (y >= t && z <= f)  
{  
return s[si];  
}  
int m = (y + z) / 2;  
return getSumUtil(y, m, t, f, 2 * si + 1) +  
getSumUtil(m + 1, z, t, f, 2 * si + 2);  
}  
int getSum(int t, int y, int z)  
{ 
if (y < 0 || z > t - 1 || y > z)  
{  
System.out.println("Invalid input");  
return -1;  
}  
return getSumUtil(0, t - 1, y, z, 0);  
}  
void constructSTUtil(int b[], int y, int z, int si)  
{
if (y > z)  
{  
return;  
} 
if (y == z)  
{  
s[si] = b[y];  
return;  
}  
int m = (y + z) / 2;  
constructSTUtil(b, y, m, 2 * si + 1);  
constructSTUtil(b, m + 1, z, 2* si + 2);  
s[si] = s[2 * si + 1] + s[2 * si + 2];  
}  
void constructST(int b[], int t)  
{  
constructSTUtil(b, 0, t - 1, 0);  
}  
public static void main(String argvs[])  
{  
int b[] = {3, 5, 8, 11, 13, 14};  
int t = b.length;  
LSTE1 tObj = new LSTE1();  
tObj.constructST(b, t);  
System.out.println(" In the given range sum of the values is: " +  
tObj.getSum(t, 2, 5));  
tObj.updateRange(t, 2, 10, 8);  
System.out.println("In the given range the sum of the values, after updation is: " +  
tObj.getSum(t, 2, 5));  
}  
}   

Output:

Lazy Propagation in Segment Tree in Java

Related Topics

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

String Handling Method in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.