Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save daubattu/dde5c99dc947fb99e798798b24c50de2 to your computer and use it in GitHub Desktop.
Save daubattu/dde5c99dc947fb99e798798b24c50de2 to your computer and use it in GitHub Desktop.
[Hackerrank] Solution of Divisible Sum Pairs in JavaScript
function divisibleSumPairs(n, k, ar) {
let result = 0;
for(let i = 0; i < n - 1; i++) {
result += ar.slice(i + 1, n).filter((item, index) => {
if ((item + ar[i]) % k === 0) {
return item;
}
}).length;
}
return result;
}
@bhupati0001
Copy link

`function divisibleSumPairs(n, k, ar) {
let count = 0;
let remainderCounts = new Array(k).fill(0);

// Count the occurrences of each remainder
for (let i = 0; i < n; i++) {
    let remainder = ar[i] % k;
    if (remainder < 0) remainder += k; // Handle negative remainders
    remainderCounts[remainder]++;
}

// Count pairs where the sum of remainders is divisible by k
for (let r = 0; r <= k / 2; r++) {
    if (r === 0 || (2 * r === k)) {
        // Special case for remainder 0 or k/2 (when k is even)
        count += (remainderCounts[r] * (remainderCounts[r] - 1)) / 2;
    } else {
        count += remainderCounts[r] * remainderCounts[k - r];
    }
}

return count;

}
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment