Count of triplets in an array that satisfy the given conditions | Python3 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
MAX = 100001 NEW_LINE ROW = 10 NEW_LINE COL = 3 NEW_LINE indices = [ 0 ] * MAX NEW_LINE 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 ] ] NEW_LINE def find_triplet ( array , n ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT indices [ i ] = [ ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT indices [ array [ i ] ] . append ( i ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT y = array [ i ] NEW_LINE for j in range ( ROW ) : NEW_LINE INDENT s = test [ j ] [ 1 ] * y NEW_LINE if s % test [ j ] [ 0 ] != 0 : NEW_LINE INDENT continue NEW_LINE DEDENT if s % test [ j ] [ 2 ] != 0 : NEW_LINE INDENT continue NEW_LINE DEDENT x = s // test [ j ] [ 0 ] NEW_LINE z = s // test [ j ] [ 2 ] NEW_LINE if x > MAX or z > MAX : NEW_LINE INDENT continue NEW_LINE DEDENT l = 0 NEW_LINE r = len ( indices [ x ] ) - 1 NEW_LINE first = - 1 NEW_LINE while l <= r : NEW_LINE INDENT m = ( l + r ) // 2 NEW_LINE if indices [ x ] [ m ] < i : NEW_LINE INDENT first = m NEW_LINE l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 NEW_LINE DEDENT DEDENT l = 0 NEW_LINE r = len ( indices [ z ] ) - 1 NEW_LINE third = - 1 NEW_LINE while l <= r : NEW_LINE INDENT m = ( l + r ) // 2 NEW_LINE if indices [ z ] [ m ] > i : NEW_LINE INDENT third = m NEW_LINE r = m - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT DEDENT if first != - 1 and third != - 1 : NEW_LINE INDENT answer += ( first + 1 ) * ( len ( indices [ z ] ) - third ) NEW_LINE DEDENT DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT array = [ 2 , 4 , 5 , 6 , 7 ] NEW_LINE n = len ( array ) NEW_LINE print ( find_triplet ( array , n ) ) NEW_LINE DEDENT