Last active
December 4, 2019 21:17
-
-
Save jaruesink/de72fb5b9fdf20753fadaea4fff6c163 to your computer and use it in GitHub Desktop.
RainforestQA Interview Question
This file contains hidden or 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
const sampleData = [0, 1, 100, 99, 0, 10, 90, 30, 55, 50, 33, 49, 49, 55, 75, 51, 49, 50, 51, 50, 49, 51]; | |
const findUniquePairsThatSumToA = (summedValue, data) => { | |
const usedValues = new Map([]); | |
return data.reduce((acc, dataValue) => { | |
const matchingPairUsedCount = usedValues.get(summedValue - dataValue) || 0; | |
const matchingPairUsed = usedValues.has(summedValue - dataValue); | |
if (matchingPairUsed && matchingPairUsedCount === 1) acc.push([dataValue, summedValue - dataValue]); | |
usedValues.set(summedValue - dataValue, matchingPairUsedCount + 1); | |
return acc; | |
}, []); | |
}; | |
console.log(findUniquePairsThatSumToA(100, sampleData)); | |
const findUniquePairsThatSumToB = (summedValue, data) => { | |
const output = []; | |
data = data.sort((a, b) => a - b); | |
let leftIndex = 0; | |
let rightIndex = data.length - 1; | |
const valuePairsMatchSum = () => | |
data[leftIndex] + data[rightIndex] === summedValue; | |
const valuePairsGreaterThanSum = () => | |
data[leftIndex] + data[rightIndex] > summedValue; | |
const valuePairsLessThanSum = () => | |
data[leftIndex] + data[rightIndex] < summedValue; | |
const addPairToOutput = () => | |
output.push([data[leftIndex], data[rightIndex]]); | |
const moveLeftIndex = () => { | |
const currentValue = data[leftIndex]; | |
while (currentValue === data[leftIndex]) leftIndex++; | |
}; | |
const moveRightIndex = () => { | |
const currentValue = data[rightIndex]; | |
while (currentValue === data[rightIndex]) rightIndex--; | |
}; | |
const crunch = () => { | |
if (leftIndex >= rightIndex) return output; | |
if (valuePairsMatchSum()) { | |
addPairToOutput(); | |
moveLeftIndex(); | |
moveRightIndex(); | |
} | |
if (valuePairsLessThanSum()) moveLeftIndex(); | |
if (valuePairsGreaterThanSum()) moveRightIndex(); | |
crunch(); | |
return output; | |
}; | |
return crunch(); | |
} | |
console.log(findUniquePairsThatSumToB(100, sampleData)); |
Adding a fun way that only needs to walk through half of the array, but requires it to be sorted first.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In my previous revision utilizing a Set, I realized that having multiple duplicate numbers such as 3 50s would throw it off. Using a Map simplifies the logic and allows me to keep a count of which paired numbers I have already used.