Skip to content

Instantly share code, notes, and snippets.

@ubershmekel
Created December 2, 2020 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ubershmekel/c38bb570b57dfc997b0f7d8777bcc549 to your computer and use it in GitHub Desktop.
Save ubershmekel/c38bb570b57dfc997b0f7d8777bcc549 to your computer and use it in GitHub Desktop.
From 2020-11-29 cassidy@cassidoo.co newsletter challenge 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.
/*
From 2020-11-29 cassidy@cassidoo.co newsletter challenge
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}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment