Count pairs that add up to a given sum “k”.
Problem Description: Find the number of pairs in a given array arr
that add up to produce a given number k
.
Basic Approach:
function findPairs(arr, k) {
let numOfPairs = 0;
// 'numerOfPairs' will return double the actual number of pairs because of nested iteration
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (arr[i] + arr[j] === k) {
numOfPairs++;
}
}
}
// dividing 'numOfPairs' by 2 to avoid duplicate results
let actualNumOfPairs = numOfPairs/2;
return actualNumOfPairs;
}
const arr = [1, 5, 5, 7, -1];
const k = 6;
const result = findPairs(arr, k);
console.log(result);
Better Approach:
function findAddingPairs(nums, k) {
let count = 0;
let mp = new Map();
for (let i = 0; i < nums.length; i++) {
let b = k - nums[i];
// increasing 'count' by number of previous occurences of 'b'
if (mp.has(b)) {
count += mp.get(b);
}
if (mp.has(nums[i])) {
// if 'nums[i]' exists already => incrementing the value/frequency by 1
mp.set(nums[i], mp.get(nums[i])+1);
} else {
// if 'nums[i]' doesn't exist => set as new value
mp.set(nums[i], 1);
}
}
return count;
};
const arr = [1, 2, 3, 4, 0, -1];
const k = 3;
const result = findAddingPairs(arr, k);
console.log(result);