Count triplets from a sorted array having difference between adjacent elements equal to D | 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
function countTriplets ( D , arr ) { var freq = new Map ( ) ; var ans = 0 ; var i ; for ( i = 0 ; i < arr . length ; i ++ ) { if ( freq . has ( arr [ i ] - D ) && freq . has ( arr [ i ] - 2 * D ) ) { ans += freq . get ( arr [ i ] - D ) * freq . get ( arr [ i ] - 2 * D ) ; } freq . set ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; } return ans ; } var arr = [ 1 , 2 , 4 , 5 , 7 , 8 , 10 ] ; var D = 1 ; document . write ( countTriplets ( D , arr ) ) ;