Find the number of elements X such that X + K also exists in the array | Java implementation of find number of elements x in this array such x + k also present in this 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
import java . util . * ; class GFG { static int count_element ( int N , int K , int [ ] arr ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; ++ i ) if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } int answer = 0 ; for ( Map . Entry < Integer , Integer > i : mp . entrySet ( ) ) { if ( mp . containsKey ( i . getKey ( ) + K ) ) answer += i . getValue ( ) ; } return answer ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 6 , 2 , 8 , 7 , 6 , 5 , 9 } ; int N = arr . length ; int K = 2 ; System . out . print ( count_element ( N , K , arr ) ) ; } }