Posts

Showing posts with the label Segment Tree

Lazy Propagation - Too lazy to update all at a time

Image
Sometimes problems will ask you to update an interval from  l to r , instead of a single element. One solution is to update all the elements one by one. Complexity of this approach will be  O(N)  per operation since where are  N  elements in the array and updating a single element will take  O(logN)  time. To avoid multiple call to update function, we can modify the update function to work on an interval. For example consider the node with value 27 in above diagram, this node stores sum of values at indexes from 3 to 5. If our update query is for range 2 to 5, then we need to update this node and all descendants of this node. With Lazy propagation, we update only node with value 27 and postpone updates to its children by storing this update information in separate nodes called lazy nodes or values. We create an array lazy[] which represents lazy node. Size of lazy[] is same as array that represents segment tree, which is tree[] in below cod...

Segment Tree

Image
Segment Tree is used in cases where there are multiple range queries on array and modifications of elements of the same array. For example, finding the sum of all the elements in an array from indices  L  to  R , or finding the minimum (famously known as Range Minumum Query problem) of all the elements in an array from indices  L  to  R . These problems can be easily solved with one of the most versatile data structures,  Segment Tree .       Notes: The root of the segment tree contains the whole array A[0: N-1] There are N leaves representing theN elements of the array.  The number of internal nodes is N−1.  Total number of nodes are 2*N-1. Operations( Templates) :- Build :  void build ( int node , int start , int end ) { if ( start == end ) { // Leaf node will have a single element tree [ node ] = A [ start ]; } else { int m...