Created
May 30, 2021 04:07
-
-
Save CarlaTeo/1072fddb4955d71c3585f0b5e19ac7db to your computer and use it in GitHub Desktop.
[JS] Pair sums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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