Queries to return the absolute difference between L | Function to return the result for a particular query ; Get the difference between the indices of L - th and the R - th smallest element ; Return the answer ; Function that performs all the queries ; Store the array numbers and their indices ; Sort the array elements ; Answer all the queries ; Driver code
def answerQuery ( arr , l , r ) : NEW_LINE INDENT answer = abs ( arr [ l - 1 ] [ 1 ] - arr [ r - 1 ] [ 1 ] ) NEW_LINE return answer NEW_LINE DEDENT def solveQueries ( a , n , q , m ) : NEW_LINE INDENT arr = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] [ 0 ] = a [ i ] NEW_LINE arr [ i ] [ 1 ] = i NEW_LINE DEDENT arr . sort ( reverse = False ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT print ( answerQuery ( arr , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 5 , 4 , 2 , 8 , 6 , 7 ] NEW_LINE n = len ( a ) NEW_LINE q = [ [ 2 , 5 ] , [ 1 , 3 ] , [ 1 , 5 ] , [ 3 , 6 ] ] NEW_LINE m = len ( q ) NEW_LINE solveQueries ( a , n , q , m ) NEW_LINE DEDENT