Skip to content

Instantly share code, notes, and snippets.

@jaruesink
Last active December 4, 2019 21:17
Show Gist options
  • Save jaruesink/de72fb5b9fdf20753fadaea4fff6c163 to your computer and use it in GitHub Desktop.
Save jaruesink/de72fb5b9fdf20753fadaea4fff6c163 to your computer and use it in GitHub Desktop.
RainforestQA Interview Question
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));
@jaruesink
Copy link
Author

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.

@jaruesink
Copy link
Author

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