Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active March 12, 2025 20:24
Show Gist options
  • Save primaryobjects/308d92d923269e9339aed3962368a4bb to your computer and use it in GitHub Desktop.
Save primaryobjects/308d92d923269e9339aed3962368a4bb to your computer and use it in GitHub Desktop.
Sum of Power of Twos and Lookup Table CodeSignal question https://codesignal.com/blog/interview-prep/example-codesignal-questions/
const countSumPowerTwo = arr => {
let result = 0;
const hash = {};
// Iterate each number in the array.
for (let i=0; i<arr.length; i++) {
const element = arr[i];
const powerOfTwos = [];
// Increment the count for the occurrence of this element.
hash[element] = hash[element] ? hash[element] + 1 : 1;
// Calculate the remainder from each power of two from this element.
for (let j=0; j<21; j++) {
const powerOfTwo = 1 << j;
const remainder = powerOfTwo - element;
// Add the count of all occurrences of this remainder.
result += hash[remainder] ? hash[remainder] : 0;
}
}
return result;
}
console.log(countSumPowerTwo([1, -1, 2, 3]));
console.log(countSumPowerTwo([2]));
console.log(countSumPowerTwo([-2, -1, 0, 1, 2]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment