Pairs with difference K
The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol n.
The following line contains n space separated integers, that denote the value of the elements of the array.
The following line contains an integer, that denotes the value of K.
The first and only line of output contains count of all such pairs which have an absolute difference of K.
0 <= n <= 10^4
Time Limit: 1 sec
4
5 1 2 4
3
2
4
4 4 4 4
0
6
#include <unordered_map>int getPairsWithDifferenceK(int *arr, int n, int k) { // Write your code here unordered_map <int,int> st; int ans = 0; for (int i=0;i<n;i++){ // num - comp = k // comp = num - k || k- num if (st.count(k+arr[i])){ ans += st[k+arr[i]]; } else if (st.count(arr[i]-k)){ ans += st[arr[i]-k]; }
st[arr[i]]++; } return ans;}
Comments
Post a Comment