Find the distance between two person after reconstruction of queue | Function to find the correct order and then return the distance between the two persons ; Make pair of both height & infront and insert to vector ; Sort the vector in ascending order ; Find the correct place for every person ; Insert into position vector according to infront value ; Driver code
function getDistance ( arr , n , a , b ) { let vp = [ ] ; for ( let i = 0 ; i < n ; i ++ ) { vp . push ( [ arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ] ) ; } vp . sort ( function ( c , d ) { return c [ 0 ] - d [ 0 ] ; } ) ; let pos = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { pos [ i ] = 0 ; } for ( let i = 0 ; i < vp . length ; i ++ ) { let height = vp [ i ] [ 0 ] ; let k = vp [ i ] [ 1 ] ; pos [ k ] = height } let first = - 1 , second = - 1 ; for ( let i = 0 ; i < pos . length ; i ++ ) { if ( pos [ i ] == a ) first = i ; if ( pos [ i ] == b ) second = i ; } return Math . abs ( first - second ) ; } let arr = [ [ 5 , 0 ] , [ 3 , 0 ] , [ 2 , 0 ] , [ 6 , 4 ] , [ 1 , 0 ] , [ 4 , 3 ] ] ; let n = arr . length ; let a = 6 , b = 5 ; document . write ( getDistance ( arr , n , a , b ) ) ;