Pairs Solution

carlosbf
1 min readSep 17, 2018

This is one of the medium difficulty problems in the search section of Hackerrank’s interview preparation kit problem set. Link here.

The problem states that given an array, you need to find all pairs a, b such that a-b = k. The items of the array are 32 bit positive integers, no zeros. k is also positive non-zero. Also each item in the array is unique

Solution

The solution is very simple. Since we are dealing with non-negative and non-zero integers. To know how many pairs there are we make the following observation. Since our pairs fullfill the condition arr[i]-arr[j] =k. Then
arr[i]=arr[j] + k. If we count all arr[j] + k then if we look up all arr[i] in the hashmap and we get our solution. Since we deal with non-negative non-zero unique element array this simple solution works.

Code

Link to github solution

int pairs(int k, vector<int> arr) {
int sol = 0;
int n = arr.size();
unordered_map<int, int> count;

for(int i = 0; i < n; i++)
count[k+arr[i]] = 1;

for(int i = 0; i < n; i++)
sol+=count[arr[i]];

return sol;
}

--

--

carlosbf

Software developer that publishes his interview prep on this blog