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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int D , vector < int > & arr ) { unordered_map < int , int > freq ; int ans = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( freq . find ( arr [ i ] - D ) != freq . end ( ) && freq . find ( arr [ i ] - 2 * D ) != freq . end ( ) ) { ans += freq [ arr [ i ] - D ] * freq [ arr [ i ] - 2 * D ] ; } freq [ arr [ i ] ] ++ ; } return ans ; } int main ( ) { vector < int > arr { 1 , 2 , 4 , 5 , 7 , 8 , 10 } ; int D = 1 ; cout << countTriplets ( D , arr ) ; return 0 ; }