JSFiddle - React, Tailwind, and code Playground
by ubershmekel
JavaScript
/* Given an array of integers and a target value, return the number of pairs of array elements that have a difference equal to a target value.
Examples:
$ arrayDiff([1, 2, 3, 4], 1)
$ 3 // 2 - 1 = 1, 3 - 2 = 1, and 4 - 3 = 1
*/
function arrayDiffBrute(arr, target) {
let pairCount = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (Math.abs(arr[i] - arr[j]) === target) {
pairCount++;
}
}
}
return pairCount;
}
function arrayDiff(arr, target) {
let pairCount = 0;
let valToIndex = {};
for (let i = 0; i < arr.length; i++) {
if (!valToIndex[arr[i]]) {
valToIndex[arr[i]] = []
}
valToIndex[arr[i]].push(i);
}
for (let i = 0; i < arr.length; i++) {
diffTarget = arr[i] + target;
if (valToIndex[diffTarget]) {
pairCount += valToIndex[diffTarget].length;
}
}
return pairCount;
}
const tests = [
{
arr: [1, 2, 3, 4],
target: 1,
expected: 3,
},
{
arr: [1, 4],
target: 1,
expected: 0,
},
{
arr: [1, 4],
target: 3,
expected: 1,
},
{
arr: [1, 4, 9, 14],
target: 5,
expected: 2,
},
];
for (const test of tests) {
const result = arrayDiff(test.arr, test.target);
console.log(`arr: ${test.arr}, expected: ${test.expected}, got: ${result}`);
}