Count of triplets in an array that satisfy the given conditions | Javascript implementation of the approach ; All possible solutions of the equation 1 / a + 1 / b + 1 / c = 1 ; Function to find the triplets ; Storing indices of the elements ; Check if y can act as the middle element of triplet with the given solution of 1 / a + 1 / b + 1 / c = 1 ; Binary search to find the number of possible values of the first element ; Binary search to find the number of possible values of the third element ; Contribution to the answer would be the multiplication of the possible values for the first and the third element ; Driver code
var MAX = 100001 var ROW = 10 var COl = 3 var indices = Array . from ( Array ( MAX ) , ( ) => new Array ( ) ) ; var test = [ [ 2 , 3 , 6 ] , [ 2 , 4 , 4 ] , [ 2 , 6 , 3 ] , [ 3 , 2 , 6 ] , [ 3 , 3 , 3 ] , [ 3 , 6 , 2 ] , [ 4 , 2 , 4 ] , [ 4 , 4 , 2 ] , [ 6 , 2 , 3 ] , [ 6 , 3 , 2 ] ] ; function find_triplet ( array , n ) { var answer = 0 ; for ( var i = 0 ; i < n ; i ++ ) { indices [ array [ i ] ] . push ( i ) ; } for ( var i = 0 ; i < n ; i ++ ) { var y = array [ i ] ; for ( var j = 0 ; j < ROW ; j ++ ) { var s = test [ j ] [ 1 ] * y ; if ( s % test [ j ] [ 0 ] != 0 ) continue ; if ( s % test [ j ] [ 2 ] != 0 ) continue ; var x = s / test [ j ] [ 0 ] ; var z = s / test [ j ] [ 2 ] ; if ( x > MAX z > MAX ) continue ; var l = 0 ; var r = indices [ x ] . length - 1 ; var first = - 1 ; while ( l <= r ) { var m = ( l + r ) / 2 ; if ( indices [ x ] [ m ] < i ) { first = m ; l = m + 1 ; } else { r = m - 1 ; } } l = 0 ; r = indices [ z ] . length - 1 ; var third = - 1 ; while ( l <= r ) { var m = ( l + r ) / 2 ; if ( indices [ z ] [ m ] > i ) { third = m ; r = m - 1 ; } else { l = m + 1 ; } } if ( first != - 1 && third != - 1 ) { answer += ( first + 1 ) * ( indices [ z ] . length - third ) ; } } } return answer ; } var array = [ 2 , 4 , 5 , 6 , 7 ] ; var n = array . length ; document . write ( find_triplet ( array , n ) ) ;