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
function answerQuery ( arr , l , r ) { let answer = Math . abs ( arr [ l - 1 ] [ 1 ] - arr [ r - 1 ] [ 1 ] ) ; return answer ; } function solveQueries ( a , n , q , m ) { let arr = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { arr [ i ] = new Array ( n ) . fill ( 0 ) } for ( let i = 0 ; i < n ; i ++ ) { arr [ i ] [ 0 ] = a [ i ] ; arr [ i ] [ 1 ] = i ; } arr . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] ) ; for ( let i = 0 ; i < m ; i ++ ) document . write ( answerQuery ( arr , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) + " " ) ; } let a = [ 1 , 5 , 4 , 2 , 8 , 6 , 7 ] ; let n = a . length ; let q = [ [ 2 , 5 ] , [ 1 , 3 ] , [ 1 , 5 ] , [ 3 , 6 ] ] ; let m = q . length ; solveQueries ( a , n , q , m ) ;