Queries to return the absolute difference between L | Java implementation of the approach ; pair class ; 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 pair ; Sort the array elements ; Answer all the queries ; Driver code
import java . util . * ; import java . util . Comparator ; class GFG { static class pair { int first , second ; pair ( int f , int s ) { first = f ; second = s ; } } static int answerQuery ( pair arr [ ] , int l , int r ) { int answer = Math . abs ( arr [ l - 1 ] . second - arr [ r - 1 ] . second ) ; return answer ; } static void solveQueries ( int a [ ] , int n , int q [ ] [ ] , int m ) { pair arr [ ] = new pair [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = new pair ( 0 , 0 ) ; arr [ i ] . first = a [ i ] ; arr [ i ] . second = i ; } Comparator < pair > comp = new Comparator < pair > ( ) { public int compare ( pair e1 , pair e2 ) { if ( e1 . first < e2 . first ) { return - 1 ; } else if ( e1 . first > e2 . first ) { return 1 ; } else { return 0 ; } } } ; Arrays . sort ( arr , comp ) ; for ( int i = 0 ; i < m ; i ++ ) System . out . println ( answerQuery ( arr , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) ) ; } public static void main ( String args [ ] ) { int a [ ] = { 1 , 5 , 4 , 2 , 8 , 6 , 7 } ; int n = a . length ; int q [ ] [ ] = { { 2 , 5 } , { 1 , 3 } , { 1 , 5 } , { 3 , 6 } } ; int m = q . length ; solveQueries ( a , n , q , m ) ; } }