Find the number of elements X such that X + K also exists in the array | Function to return the count of element x such that x + k also lies in this array ; Key in map will store elements and value will store the frequency of the elements ; Find if i . first + K is present in this map or not ; If we find i . first or key + K in this map then we have to increase in answer the frequency of this element ; Driver code ; array initialisation ; size of array ; initialise k
def count_element ( N , K , arr ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT mp [ arr [ i ] ] = mp . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT answer = 0 NEW_LINE for i in mp : NEW_LINE INDENT if i + K in mp : NEW_LINE INDENT answer += mp [ i ] NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 6 , 2 , 8 , 7 , 6 , 5 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( count_element ( N , K , arr ) ) NEW_LINE DEDENT