Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created May 30, 2021 04:07
Show Gist options
  • Save CarlaTeo/1072fddb4955d71c3585f0b5e19ac7db to your computer and use it in GitHub Desktop.
Save CarlaTeo/1072fddb4955d71c3585f0b5e19ac7db to your computer and use it in GitHub Desktop.
[JS] Pair sums
// Given a list of integers determine the number of different pairs of elements within it which sum to k.
function numberOfWays(arr, k) {
let counter = 0;
const indexesByModK = {};
arr.forEach((num, j) => {
const modK = num % k;
const modKComplement = (k - modK) % k;
if(Object.keys(indexesByModK).includes(String(modKComplement))) {
counter += indexesByModK[modKComplement].length;
}
if(indexesByModK[modK]) indexesByModK[modK].push(j);
else indexesByModK[modK] = [j];
});
return counter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment