Count of triplets in an Array such that A [ i ] * A [ j ] = A [ k ] and i < j < k | Python3 program for the above approach ; Returns total number of valid triplets possible ; Stores the count ; Map to store frequency of array elements ; Increment the frequency of A [ j + 1 ] as it can be a valid A [ k ] ; If target exists in the map ; Return the final count ; Driver code
from collections import defaultdict NEW_LINE def countTriplets ( A , N ) : NEW_LINE INDENT ans = 0 NEW_LINE map = defaultdict ( lambda : 0 ) NEW_LINE for j in range ( N - 2 , 0 , - 1 ) : NEW_LINE INDENT map [ A [ j + 1 ] ] += 1 NEW_LINE for i in range ( j ) : NEW_LINE INDENT target = A [ i ] * A [ j ] NEW_LINE if ( target in map . keys ( ) ) : NEW_LINE INDENT ans += map [ target ] NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE A = [ 2 , 3 , 4 , 6 , 12 ] NEW_LINE print ( countTriplets ( A , N ) ) NEW_LINE DEDENT