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 ; array initialisation ; size of array ; initialise k
function count_element ( N , K , arr ) { let mp = new Map ( ) ; for ( let i = 0 ; i < N ; ++ i ) if ( mp . has ( arr [ i ] ) ) { mp . set ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) } else { mp . set ( arr [ i ] , 1 ) } let answer = 0 ; for ( let i of mp ) { if ( mp . has ( i [ 0 ] + K ) ) answer += i [ 1 ] ; } return answer ; } let arr = [ 3 , 6 , 2 , 8 , 7 , 6 , 5 , 9 ] ; let N = arr . length ; let K = 2 ; document . write ( count_element ( N , K , arr ) ) ;