Count triplets from a sorted array having difference between adjacent elements equal to D | Java program for the above approach ; Function to count the number of triplets having difference between adjacent elements equal to D ; Stores the frequency of array elements ; Stores the count of resultant triplets ; Traverse the array ; Check if arr [ i ] - D and arr [ i ] - 2 * D exists in the Hashmap or not ; Update the value of ans ; Increase the frequency of the current element ; Return the resultant count ; Driver Code
import java . util . * ; class GFG { static int countTriplets ( int D , int [ ] arr ) { HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; int ans = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( freq . containsKey ( arr [ i ] - D ) && freq . containsKey ( arr [ i ] - 2 * D ) ) { ans += freq . get ( arr [ i ] - D ) * freq . get ( arr [ i ] - 2 * D ) ; } if ( freq . containsKey ( arr [ i ] ) ) { freq . put ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; } else { freq . put ( arr [ i ] , 1 ) ; } } return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 5 , 7 , 8 , 10 } ; int D = 1 ; System . out . print ( countTriplets ( D , arr ) ) ; } }