Queries to return the absolute difference between L | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int answerQuery ( pair < int , int > arr [ ] , int l , int r ) { int answer = abs ( arr [ l - 1 ] . second - arr [ r - 1 ] . second ) ; return answer ; } void solveQueries ( int a [ ] , int n , int q [ ] [ 2 ] , int m ) { pair < int , int > arr [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] . first = a [ i ] ; arr [ i ] . second = i ; } sort ( arr , arr + n ) ; for ( int i = 0 ; i < m ; i ++ ) cout << answerQuery ( arr , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) << endl ; } int main ( ) { int a [ ] = { 1 , 5 , 4 , 2 , 8 , 6 , 7 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int q [ ] [ 2 ] = { { 2 , 5 } , { 1 , 3 } , { 1 , 5 } , { 3 , 6 } } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; solveQueries ( a , n , q , m ) ; return 0 ; }