Range sum queries for anticlockwise rotations of Array by K indices | Java program to calculate range sum queries for anticlockwise rotations of array by K ; Function to execute the queries ; Construct a new array of size 2 * N to store prefix sum of every index ; Copy elements to the new array ; Calculate the prefix sum for every index ; Set start pointer as 0 ; Query to perform anticlockwise rotation ; Query to answer range sum ; If pointing to 1 st index ; Display the sum upto start + R ; Subtract sum upto start + L - 1 from sum upto start + R ; Driver code ; Number of query ; Store all the queries
class GFG { static void rotatedSumQuery ( int arr [ ] , int n , int [ ] [ ] query , int Q ) { int [ ] prefix = new int [ 2 * n ] ; for ( int i = 0 ; i < n ; i ++ ) { prefix [ i ] = arr [ i ] ; prefix [ i + n ] = arr [ i ] ; } for ( int i = 1 ; i < 2 * n ; i ++ ) prefix [ i ] += prefix [ i - 1 ] ; int start = 0 ; for ( int q = 0 ; q < Q ; q ++ ) { if ( query [ q ] [ 0 ] == 1 ) { int k = query [ q ] [ 1 ] ; start = ( start + k ) % n ; } else if ( query [ q ] [ 0 ] == 2 ) { int L , R ; L = query [ q ] [ 1 ] ; R = query [ q ] [ 2 ] ; if ( start + L == 0 ) System . out . print ( prefix [ start + R ] + "NEW_LINE"); else System . out . print ( prefix [ start + R ] - prefix [ start + L - 1 ] + "NEW_LINE"); } } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int Q = 5 ; int [ ] [ ] query = { { 2 , 1 , 3 } , { 1 , 3 } , { 2 , 0 , 3 } , { 1 , 4 } , { 2 , 3 , 5 } } ; int n = arr . length ; rotatedSumQuery ( arr , n , query , Q ) ; } }