VOOZH about

URL: https://www.geeksforgeeks.org/dsa/flipping-sign-problem-lazy-propagation-segment-tree/

⇱ Flipping Sign Problem | Lazy Propagation Segment Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Flipping Sign Problem | Lazy Propagation Segment Tree

Last Updated : 12 Jul, 2025

Given an array of size N. There can be multiple queries of the following types.  

  1. update(l, r) : On update, flip( multiply a[i] by -1) the value of a[i] where l <= i <= r . In simple terms, change the sign of a[i] for the given range.
  2. query(l, r): On query, print the sum of the array in given range inclusive of both l and r.

Examples :

Input : arr[] = { 1, 2, 3, 4, 5 } 
update(0, 2) 
query(0, 4) 
Output:
After applying update operation array becomes { -1, -2, -3, 4, 5 } . 
So the sum is 3

Input : arr[] = { 1, 2, 3, 4, 5 } 
update(0, 4) 
query(0, 4) 
Output: -15 
After applying update operation array becomes { -1, -2, -3, -4, -5 } . 
So the sum is -15 

Prerequisites: 

  1. Segment tree
  2. Lazy propagation in segment tree

Approach : 
Create a segment tree where every node store the sum of its left and right child unless it is a leaf node where the array is stored.
For update operation: 
Create a tree named lazy of size same as the above segment tree where tree store the sum of its child and lazy stores whether they have been asked to be flipped or not. If lazy is set to 1 for a range then all value under that range needs to be flipped. For update following operation are used - 
 

  • If current segment tree has lazy set to 1 then update current segment tree node by changing the sign as value needs to be flipped and also flip the value of lazy of its child and reset its own lazy to 0.
  • If current node's range lies completely in update query range then update the current node by changing its sign and also flip value of lazy of its child if not leaf node.
  • If current node's range overlaps with update range then do recursion for its children and update the current node using the sum of its children.

For query operation: 
If lazy is set to 1 then change the sign of the current node and reset current node lazy to 0 and also flip the value of lazy of its child if not leaf node. And then do simple query as done in segment tree .

Below is the implementation of the above approach : 


Output: 
15
-15
-3

 

Time Complexity : O(log(N))
Auxiliary Space: O(log(N)), due to recursive call stacks.

Related Topic: Segment Tree

Comment