![]() |
VOOZH | about |
Given an array of size N. There can be multiple queries of the following types.
Examples :
Input : arr[] = { 1, 2, 3, 4, 5 }
update(0, 2)
query(0, 4)
Output: 3
After applying update operation array becomes { -1, -2, -3, 4, 5 } .
So the sum is 3Input : 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:
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 -
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 :
15 -15 -3
Time Complexity : O(log(N))
Auxiliary Space: O(log(N)), due to recursive call stacks.
Related Topic: Segment Tree