Pairs — HackerRank Medium (Search)

iAwale
1 min readMar 19, 2020

Link to problem

Link to solution

The problem requires us to find the number of pairs that result in the target value when subtraction is performed.

The approach I am using here is,

For example we are given a set of 1 3 5 8 6 4 2. If we add the target value e.g 2 to each element, we get a new set of 3 5 7 10 8 6 4. If we count the intersected elements between these two sets we get the required count of possible pairs.

static int pairs(int k, int[] arr) {
int count = 0;
HashSet<Integer> hset = new HashSet<>();
for(int i = 0; i < arr.length; i++){
hset.add(arr[i]);
arr[i] = arr[i] + k;
}
for(int i: arr){
if(hset.contains(i)){
count++;
}
}
return count;
}

--

--

iAwale

Learn Productivity. Learn Growth. Learn Coding. Learn to Build Applications. If you like the content please follow Twitter Youtube