Find the number of elements X such that X + K also exists in the array | C # 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
using System ; using System . Collections . Generic ; public class GFG { static int count_element ( int N , int K , int [ ] arr ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < N ; ++ i ) if ( mp . ContainsKey ( arr [ i ] ) ) { mp [ arr [ i ] ] = mp [ arr [ i ] ] + 1 ; } else { mp . Add ( arr [ i ] , 1 ) ; } int answer = 0 ; foreach ( KeyValuePair < int , int > i in mp ) { if ( mp . ContainsKey ( i . Key + K ) ) answer += i . Value ; } 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 ; Console . Write ( count_element ( N , K , arr ) ) ; } }