I strucked at the line 11th line of the code , can we return the code insted of doing that , i am getting confused.
var findPairs = function(nums, k) {
let prev = {} , pairs = 0;
nums.sort((a,b)=>a-b);
for(var i=0;i<nums.length;i++){
let key = nums[i];
if(!prev[key]){
let diff = key - k;
if(prev[diff]!==undefined){
pairs++;
}
prev[key] = 1;
}else if(k===0){
if(prev[key]===1){
pairs++
}
prev[key]++;
}
}
return pairs;
};
I made a lot of assumptions, but if my assumptions are correct you are asking why we need else if statement.
I assume that this function searches for the pairs in array that have difference k. If this is correct, then the else if case is needed when k is 0 and in array you have same element multiple times. For example:
If you have k=0 and nums=[3, 4, 5, 3], we have to count 3 and 3 since they are the pairs too.