Perform range sum queries on string as per given condition | Java program for the above approach ; Function to perform range sum queries on String as per the given condition ; Initialize N by String size ; Create array A [ ] for prefix sum ; Iterate till N ; Traverse the queries ; Check if if L == 1 range sum will be A [ R - 1 ] ; Condition if L > 1 range sum will be A [ R - 1 ] - A [ L - 2 ] ; Driver Code ; Given String ; Given Queries ; Function call
import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void Range_sum_query ( String S , Vector < pair > Query ) { int N = S . length ( ) ; int [ ] A = new int [ N ] ; A [ 0 ] = S . charAt ( 0 ) - ' a ' + 1 ; for ( int i = 1 ; i < N ; i ++ ) { A [ i ] = S . charAt ( i ) - ' a ' + 1 ; A [ i ] = A [ i ] + A [ i - 1 ] ; } for ( int i = 0 ; i < Query . size ( ) ; i ++ ) { if ( Query . get ( i ) . first == 1 ) { System . out . print ( A [ ( Query . get ( i ) . second ) - 1 ] + "NEW_LINE"); } else { System . out . print ( A [ ( Query . get ( i ) . second ) - 1 ] - A [ ( Query . get ( i ) . first ) - 2 ] + "NEW_LINE"); } } } public static void main ( String [ ] args ) { String S = " abcd " ; Vector < pair > Query = new Vector < pair > ( ) ; Query . add ( new pair ( 2 , 4 ) ) ; Query . add ( new pair ( 1 , 3 ) ) ; Range_sum_query ( S , Query ) ; } }