Approach :
For this problem we can use hashmap in java (or) maps in c++ (or) dictionary in Python .
We can keep track of frequency of each element in maps.
Our task is find (a-b) which gives 2 . Suppose , we are at an element 'a' to get 'b' we should find whether a-2 exists in our array (We can do this by using the same hashmap) . If (a-2) exists , we can just add the frequency of (a-2) to our answer .
Below is the Implementation of above approach:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n=5;
vector<int> a={6,12,18,333,4};
map<int,int> m;
for(auto x:a)
{
m[x]++;
}
int ans=0;
for(auto x:a)
{
int find=x-2;
ans+=m[find];
}
cout<<ans<<endl;
return 0;
}
Input 1 :
n=5;
{ 6 ,12 , 18, 333 , 4};
output : 1 ({6-4=2})
Input 2:
n=10;
{6,12,18,333,4,4,8,6,-4,-2}
output 2 :
7 ({6,4},{6,4} , {6,8}, {4,6} ,{4,6}, {8,6} , {-4,-2} )