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
def countTriplets ( D , arr ) : NEW_LINE INDENT freq = { } NEW_LINE ans = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( ( ( arr [ i ] - D ) in freq ) and ( arr [ i ] - 2 * D ) in freq ) : NEW_LINE INDENT ans += ( freq [ arr [ i ] - D ] * freq [ arr [ i ] - 2 * D ] ) NEW_LINE DEDENT freq [ arr [ i ] ] = freq . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 5 , 7 , 8 , 10 ] NEW_LINE D = 1 NEW_LINE print ( countTriplets ( D , arr ) ) NEW_LINE DEDENT