Count the triplets such that A [ i ] < B [ j ] < C [ k ] | Function to return the count of elements in arr [ ] which are less than the given key ; Modified binary search ; Function to return the count of elements in arr [ ] which are greater than the given key ; Modified binary search ; Function to return the count of the required triplets ; Sort all three arrays ; Iterate for all the elements of array B ; Count of elements in A [ ] which are less than the chosen element from B [ ] ; Count of elements in C [ ] which are greater than the chosen element from B [ ] ; Update the count ; Driver code
function countLessThan ( arr , n , key ) { let l = 0 , r = n - 1 ; let index = - 1 ; while ( l <= r ) { let m = Math . floor ( ( l + r ) / 2 ) ; if ( arr [ m ] < key ) { l = m + 1 ; index = m ; } else { r = m - 1 ; } } return ( index + 1 ) ; } function countGreaterThan ( arr , n , key ) { let l = 0 , r = n - 1 ; let index = - 1 ; while ( l <= r ) { let m = Math . floor ( ( l + r ) / 2 ) ; if ( arr [ m ] <= key ) { l = m + 1 ; } else { r = m - 1 ; index = m ; } } if ( index == - 1 ) return 0 ; return ( n - index ) ; } function countTriplets ( n , a , b , c ) { a . sort ( function ( e , f ) { return e - f ; } ) ; b . sort ( function ( e , f ) { return e - f ; } ) ; c . sort ( function ( e , f ) { return e - f ; } ) ; let count = 0 ; for ( let i = 0 ; i < n ; ++ i ) { let current = b [ i ] ; let low = countLessThan ( a , n , current ) ; let high = countGreaterThan ( c , n , current ) ; count += ( low * high ) ; } return count ; } let a = [ 1 , 5 ] ; let b = [ 2 , 4 ] ; let c = [ 3 , 6 ] ; let size = a . length ; document . write ( countTriplets ( size , a , b , c ) ) ;