Perform range sum queries on string as per given condition | 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 ] ; Given string ; Given Queries ; Function call
function Range_sum_query ( S , Query ) { var N = S . length ; var A = Array ( N ) ; A [ 0 ] = S [ 0 ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) + 1 ; for ( var i = 1 ; i < N ; i ++ ) { A [ i ] = S [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) + 1 ; A [ i ] = A [ i ] + A [ i - 1 ] ; } for ( var i = 0 ; i < Query . length ; i ++ ) { if ( Query [ i ] [ 0 ] == 1 ) { document . write ( A [ ( Query [ i ] [ 1 ] ) - 1 ] + " " ) ; } else { document . write ( A [ ( Query [ i ] [ 1 ] ) - 1 ] - A [ ( Query [ i ] [ 0 ] ) - 2 ] + " " ) ; } } } var S = " " ; var Query = [ ] ; Query . push ( [ 2 , 4 ] ) ; Query . push ( [ 1 , 3 ] ) ; Range_sum_query ( S , Query ) ;