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;
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

iAwale
iAwale

Written by iAwale

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

No responses yet

Write a response