Skip to content
Related Articles

Related Articles

Improve Article

Queries to calculate sum of squares of array elements over range of indices [L, R] with updates

  • Difficulty Level : Hard
  • Last Updated : 13 May, 2021

Given an Array arr[] of positive integers of size n. We are required to perform following 3 queries on given array –

1) Given L and R, we have to find the sum of squares of all element lying in range [L,R]

2) Given L, R and X, we have to set all element lying in range [L,R] to X

3) Given L, R and X, we have to increment the value of all element lying in range [L,R] by X

Input Format : First line contains the number of test cases T



Next line contains two positive integers – N (Size of Array ) and Q (Number of queries to be asked).

The next line contains N integers of array

Each of the next Q lines contains the Q queries to be asked. Each line starts with a number, which indicates the  type of query followed by required input arguments. Input format for all 3 queries will look like –

0 L R X : Set all numbers in Range [L, R] to “X”

1 L R X : ADD “X” to all numbers in Range [L, R]

2 L R :  Return the sum of the squares of the numbers in Range {L, R]

Output Format : For each test case, output “Case <TestCaseNo>:” in first line and then output the sum of squares for each queries of type 2 in separate lines.

Input:
1
3 3
1 2 3
0 1 2 2
1 1 3 3
2 1 3

Output : Case 1:
         86
Explanation : With 1st query (type 0), array elements from range [1,2] will set as 2. Updated array will become [2,2,3]
              With 2nd query (type 1), array elements from range [1,3] will be incremented by 3. Updated array will become [5,5,6]
              With 3rd query (type 2), Sum of Squares for range [1,3] will be 5^2+5^2+6^2 =86
Input:              
1
4 5
1 2 3 4
2 1 4
0 3 4 1
2 1 4
1 3 4 1
2 1 4
Output : Case 1:
         30
         7
         13        

Optimized Solution



Sample Segment Tree

With the help of Segment tree with Lazy Propagation, we can perform all given queries in O(logn) time.

To know about how Segment Tree works, follow this link –https://www.geeksforgeeks.org/segment-tree-set-1-sum-of-given-range/

For this, we will create a segment tree with two variables – first one will store sum of squares in a range and other will store the sum of elements in the given range. (We will discuss this later why do we need two variables here). To update values in the given range, we will use lazy propagation technique.

For more information Regarding Lazy Propagation use link – https://www.geeksforgeeks.org/lazy-propagation-in-segment-tree/

Here if we have to set all numbers to X in a given range, then we can use this formula to update values for one particular node (which lies in given range) –

Updated Sum of squares = (R-L+1)*X*X

Updated Sum = (R-L+1)*X 

(As there are R-L+1 elements present under that particular node which need to be set as X)

If we need to increment all values in the given range [L,R] with value X, we can use this formula to update values for one particular node (which lies in given range) –

Updated Sum of square = Sum of Square in range [L,R] + (R-L+1)*X*X + 2*X*(sum in range [L,R])



Updated Sum = Sum in Range [L,R] + (R-L+1)*X 

(As there are R-L+1 elements present under that particular node which need to be incremented by X. Every node’s value can be represented as : (Previous_val + X). To calculate new sum of squares for a root node, we can use this expression –

                   (Previous_val1+ x)^2 + (Previous_val2 + x)^2 + …..  (for all child nodes)

Above expression will simplify to Sum of Square in range [L,R] + (R-L+1)*X*X + 2*X*(sum in range [L,R])

Here you can see that we need sum of elements for calculation, hence we have stored this in our segment tree along with sum of squares to fasten our calculation.

How to Update using Lazy trees

Here you can see that we need 3 lazy trees –

1. For maintaining the set update

2. For maintaining the increment by X update

3. For maintaining the order of operations, in case multiple queries come for a single node



Now creating 3 lazy trees, will not be space effective. But we can solve this by creating 1 lazy tree (change, type) with two variables – one for maintaining the update value (X) and other for type (which update we need to do increment or set).

Now to handle order of multiple queries on single node, there can two possibilities –

1) First increment and then set query – in this case we actually don’t need to increment the value, we can directly set the value to X. Because setting value of a node to X, before and after increment will remain same.

2) First set then increment query – Here effectively we are updating each node’s value as : X (set query) + X (increment query). So we can keep our type of query as set and value of change (i.e. to which nodes value will be set) as (X_set + X_increment)

For ex – arr[]=[1,2,3,4] first set [3,4] with 2 then increment [3,4] with 1

array after set query =  [1,2,2,2]

array after increment query =  [1,2,3,3]

We can achieve this in one operation by setting the value for all given range nodes as :

         (X_set + X_increment) = 2 + 1 = 3

Updated array = [1,2,3,3]



C++




// We will use 1 based indexing
// type 0 = Set
// type 1 = increment
 
 
#include<bits/stdc++.h>
using namespace std;
class segmenttree{
    public:
    int sum_of_squares;
    int sum_of_element;
};
class lazytree{
    public:
    int change;
    int type;
};
 
// Query On segment Tree
 
 
int query(segmenttree*tree,lazytree*lazy,int start,int end,int low,int high,int treeindex){
    if(lazy[treeindex].change!=0){
        int change=lazy[treeindex].change;
        int type=lazy[treeindex].type;
        if(lazy[treeindex].type==0){
            tree[treeindex].sum_of_squares=(end-start+1)*change*change;
            tree[treeindex].sum_of_element=(end-start+1)*change;
            if(start!=end){
                lazy[2*treeindex].change=change;
                lazy[2*treeindex].type=type;
                lazy[2*treeindex+1].change=change;
                lazy[2*treeindex+1].type=type;
            }
        }
        else{
            tree[treeindex].sum_of_squares+=((end-start+1)*change*change)+(2*change*tree[treeindex].sum_of_element);
            tree[treeindex].sum_of_element+=(end-start+1)*change;
            if(start!=end){
                if(lazy[2*treeindex].change==0 || lazy[2*treeindex].type==1){
                    lazy[2*treeindex].change+=change;
                    lazy[2*treeindex].type=type;
                }else{
                    lazy[2*treeindex].change+=change;
                }
                if(lazy[2*treeindex+1].change==0 || lazy[2*treeindex+1].type==1){
                    lazy[2*treeindex+1].change+=change;
                    lazy[2*treeindex+1].type=type;
                }else{
                    lazy[2*treeindex+1].change+=change;
                }
            }
        }
        lazy[treeindex].change=0;
    }
    if(start>high || end<low){
        return 0;
    }
    if(start>=low && high>=end){
        return tree[treeindex].sum_of_squares;
    }
    int mid=(start+end)/2;
    int ans=query(tree,lazy,start,mid,low,high,2*treeindex);
    int ans1=query(tree,lazy,mid+1,end,low,high,2*treeindex+1);
    return ans+ans1;
}
 
//  Update on Segment Tree
 
void update(int*arr,segmenttree*tree,lazytree*lazy,int start,int end,int low,int high,int change,int type,int treeindex){
    if(lazy[treeindex].change!=0){
        int change=lazy[treeindex].change;
        int type=lazy[treeindex].type;
        if(lazy[treeindex].type==0){
            tree[treeindex].sum_of_squares=(end-start+1)*change*change;
            tree[treeindex].sum_of_element=(end-start+1)*change;
            if(start!=end){
                lazy[2*treeindex].change=change;
                lazy[2*treeindex].type=type;
                lazy[2*treeindex+1].change=change;
                lazy[2*treeindex+1].type=type;
            }
        }
        else{
            tree[treeindex].sum_of_squares+=((end-start+1)*change*change)+(2*change*tree[treeindex].sum_of_element);
            tree[treeindex].sum_of_element+=(end-start+1)*change;
            if(start!=end){
                if(lazy[2*treeindex].change==0 || lazy[2*treeindex].type==1){
                    lazy[2*treeindex].change+=change;
                    lazy[2*treeindex].type=type;
                }else{
                    lazy[2*treeindex].change+=change;
                }
                if(lazy[2*treeindex+1].change==0 || lazy[2*treeindex+1].type==1){
                    lazy[2*treeindex+1].change+=change;
                    lazy[2*treeindex+1].type=type;
                }else{
                    lazy[2*treeindex+1].change+=change;
                }
            }
        }
        lazy[treeindex].change=0;
    }
    if(start>high || end<low){
        return;
    }
    if(start>=low && high>=end){
        if(type==0){
            tree[treeindex].sum_of_squares=(end-start+1)*change*change;
            tree[treeindex].sum_of_element=(end-start+1)*change;
            if(start!=end){
                lazy[2*treeindex].change=change;
                lazy[2*treeindex].type=type;
                lazy[2*treeindex+1].change=change;
                lazy[2*treeindex+1].type=type;
            }
        }else{
            tree[treeindex].sum_of_squares+=((end-start+1)*change*change)+(2*change*tree[treeindex].sum_of_element);
            tree[treeindex].sum_of_element+=(end-start+1)*change;
            if(start!=end){
                if(lazy[2*treeindex].change==0 || lazy[2*treeindex].type==1){
                    lazy[2*treeindex].change+=change;
                    lazy[2*treeindex].type=type;
                }else{
                    lazy[2*treeindex].change+=change;
                }
                if(lazy[2*treeindex+1].change==0 || lazy[2*treeindex+1].type==1){
                    lazy[2*treeindex+1].change+=change;
                    lazy[2*treeindex+1].type=type;
                }else{
                    lazy[2*treeindex+1].change+=change;
                }
            }
        }
        return;
    }
    int mid=(start+end)/2;
    update(arr,tree,lazy,start,mid,low,high,change,type,2*treeindex);
    update(arr,tree,lazy,mid+1,end,low,high,change,type,2*treeindex+1);
    tree[treeindex].sum_of_squares=tree[2*treeindex].sum_of_squares+tree[2*treeindex+1].sum_of_squares;
    tree[treeindex].sum_of_element=tree[2*treeindex].sum_of_element+tree[2*treeindex+1].sum_of_element;
}
 
 
// creation of segment tree
 
 
void create(int*arr,segmenttree*tree,int start,int end,int treeindex){
    if(start==end){
        tree[treeindex].sum_of_squares=start*start;
        tree[treeindex].sum_of_element=start;
        return;
    }
    int mid=(start+end)/2;
    create(arr,tree,start,mid,treeindex*2);
    create(arr,tree,mid+1,end,2*treeindex+1);
    tree[treeindex].sum_of_squares=tree[treeindex*2].sum_of_squares+tree[2*treeindex+1].sum_of_squares;
    tree[treeindex].sum_of_element=tree[treeindex*2].sum_of_element+tree[2*treeindex+1].sum_of_element;
}
int main() {
    int t;
    cin>>t;
    int case1=1;
    while(t--){
        cout<<"Case "<<case1++<<":"<<endl;
        int n,q;
        cin>>n>>q;
        int*arr=new int[n+1];
        for(int i=1;i<=n;i++){
            cin>>arr[i];
        }
        segmenttree*tree=new segmenttree[2*n];
        lazytree*lazy=new lazytree[2*n];
        create(arr,tree,1,n,1);
        while(q--){
            int type;
            cin>>type;
            if(type==2){
                int start,end;
                cin>>start>>end;
                cout<<query(tree,lazy,1,n,start,end,1)<<endl;
            }else{
                int start,end,change;
                cin>>start>>end>>change;
                update(arr,tree,lazy,1,n,start,end,change,type,1);
            }
        }
    }
}


Time Complexity:  

Time Complexity for tree construction is O(n). There are total 2n-1 nodes, and value of every node is calculated only once in tree construction.

Time complexity to query is O(Logn).

The time complexity of update is also O(Logn). 

Space Complexity : O(2*N) .

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :