Count of triplets in an Array such that A [ i ] * A [ j ] = A [ k ] and i < j < k | 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
function countTriplets ( A , N ) { let ans = 0 ; let map = new Map ( ) ; for ( let j = N - 2 ; j >= 1 ; j -- ) { if ( map . has ( A [ j + 1 ] ) ) map . set ( A [ j + 1 ] , map . get ( A [ j + 1 ] ) + 1 ) ; else map . set ( A [ j + 1 ] , 1 ) ; for ( let i = 0 ; i < j ; i ++ ) { let target = A [ i ] * A [ j ] ; if ( map . has ( target ) ) ans += map . get ( target ) ; } } return ans ; } let N = 5 ; let A = [ 2 , 3 , 4 , 6 , 12 ] ; document . write ( countTriplets ( A , N ) ) ;