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
def Range_sum_query ( S , Query ) : NEW_LINE INDENT N = len ( S ) NEW_LINE A = [ 0 ] * N NEW_LINE A [ 0 ] = ord ( S [ 0 ] ) - ord ( ' a ' ) + 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT A [ i ] = ord ( S [ i ] ) - ord ( ' a ' ) + 1 NEW_LINE A [ i ] = A [ i ] + A [ i - 1 ] NEW_LINE DEDENT for i in range ( len ( Query ) ) : NEW_LINE INDENT if ( Query [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT print ( A [ Query [ i ] [ 1 ] - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( A [ Query [ i ] [ 1 ] - 1 ] - A [ Query [ i ] [ 0 ] - 2 ] ) NEW_LINE DEDENT DEDENT DEDENT S = " abcd " NEW_LINE Query = [ ] NEW_LINE Query . append ( [ 2 , 4 ] ) NEW_LINE Query . append ( [ 1 , 3 ] ) NEW_LINE Range_sum_query ( S , Query ) NEW_LINE