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]));