Count of triplets in an Array such that A [ i ] * A [ j ] = A [ k ] and i < j < k | Java 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
import java . util . * ; class GFG { static int countTriplets ( int A [ ] , int N ) { int ans = 0 ; HashMap < Integer , Integer > map = new HashMap < Integer , Integer > ( ) ; for ( int j = N - 2 ; j >= 1 ; j -- ) { if ( map . containsKey ( A [ j + 1 ] ) ) map . put ( A [ j + 1 ] , map . get ( A [ j + 1 ] ) + 1 ) ; else map . put ( A [ j + 1 ] , 1 ) ; for ( int i = 0 ; i < j ; i ++ ) { int target = A [ i ] * A [ j ] ; if ( map . containsKey ( target ) ) ans += map . get ( target ) ; } } return ans ; } public static void main ( String [ ] args ) { int N = 5 ; int A [ ] = { 2 , 3 , 4 , 6 , 12 } ; System . out . print ( countTriplets ( A , N ) ) ; } }