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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_element ( int N , int K , int * arr ) { map < int , int > mp ; for ( int i = 0 ; i < N ; ++ i ) mp [ arr [ i ] ] ++ ; int answer = 0 ; for ( auto i : mp ) { if ( mp . find ( i . first + K ) != mp . end ( ) ) answer += i . second ; } return answer ; } int main ( ) { int arr [ ] = { 3 , 6 , 2 , 8 , 7 , 6 , 5 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << count_element ( N , K , arr ) ; return 0 ; }