Count triplets from a sorted array having difference between adjacent elements equal to D | C # 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
using System ; using System . Collections . Generic ; class GFG { static int countTriplets ( int D , int [ ] arr ) { Dictionary < int , int > freq = new Dictionary < int , int > ( ) ; 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 [ arr [ i ] - D ] * freq [ arr [ i ] - 2 * D ] ; } if ( ! freq . ContainsKey ( arr [ i ] ) ) freq [ arr [ i ] ] = 0 ; freq [ arr [ i ] ] ++ ; } return ans ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 4 , 5 , 7 , 8 , 10 } ; int D = 1 ; Console . WriteLine ( countTriplets ( D , arr ) ) ; } }