From 3e3dce5f4a775c64154fb987bfdd10c628dfbd6d Mon Sep 17 00:00:00 2001 From: Manish Date: Tue, 22 Aug 2023 10:51:35 +1000 Subject: [PATCH] Algorithms: Pairwise --- Algorithms/pairwise.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Algorithms/pairwise.js diff --git a/Algorithms/pairwise.js b/Algorithms/pairwise.js new file mode 100644 index 0000000..e318bfb --- /dev/null +++ b/Algorithms/pairwise.js @@ -0,0 +1,30 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/pairwise + +function pairwise(arr, sum) { + const arr2 = arr.map((num, index) => ({ num: num, index: index })); + arr2.sort(({ num: numA, index: indexA }, { num: numB, index: indexB }) => { + if (numA === numB) { + return indexA - indexB; + } else { + return numA - numB; + } + }); + + let [i, reverseI, pairsIndexSum] = [0, arr2.length - 1, 0]; + while (i < reverseI) { + if (arr2[i].num + arr2[reverseI].num === sum) { + if (arr2[i].num === arr2[reverseI].num) { + pairsIndexSum += arr2[i++].index + arr2[i++].index; + } else { + pairsIndexSum += arr2[i++].index + arr2[reverseI--].index; + } + } else if (arr2[i].num + arr2[reverseI].num < sum) { + i++; + } else { + reverseI--; + } + } + return pairsIndexSum; +} + +console.log(pairwise([1, 1, 1], 2));