I was going through a question where the problem was to find the number of pairs which makes a difference K.Below is the code for the same.In the below code I have used hashmap however it gave correct answer but for few of the scenario's I got timeout where as using HashSet all the test cases were passed.Can anyone help why using hashmap I am getting timeout error whereas in actual scenario hashmap computation is fast as compared to hashset.
static int pairs(int k, int[] arr) {
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<arr.length;i++)
map.put(i,arr[i]);
int count=0;
for(int j=0;j<arr.length;j++)
{
if(map.containsValue(arr[j]-k))
count++;
}
return count;
}
Correct me if my understanding is wrong.Thanks in advance for the same.