Last active
March 12, 2025 20:24
-
-
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/
This file contains 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 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