Count of triplets in an Array such that A [ i ] * A [ j ] = A [ k ] and i < j < k | C ++ Program to implement 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int A [ ] , int N ) { int ans = 0 ; map < int , int > map ; for ( int j = N - 2 ; j >= 1 ; j -- ) { map [ A [ j + 1 ] ] ++ ; for ( int i = 0 ; i < j ; i ++ ) { int target = A [ i ] * A [ j ] ; if ( map . find ( target ) != map . end ( ) ) ans += map [ target ] ; } } return ans ; } int main ( ) { int N = 5 ; int A [ ] = { 2 , 3 , 4 , 6 , 12 } ; cout << countTriplets ( A , N ) ; return 0 ; }