Count Index Pairs Where Elements Sum is Power of 2 in Python



Suppose we have a list of numbers called nums. We have to find the number of index pairs i, j, where i < j such that nums[i] + nums[j] is equal to 2^k for some 0 >= k.

So, if the input is like nums = [1, 2, 6, 3, 5], then the output will be 3, as there are three pairs sum like (6, 2): sum is 8, (5, 3): sum is 8 and (1, 3) sum is 4

To solve this, we will follow these steps −

  • res := 0

  • c := a map containing frequencies of each elements present in

  • for each x in nums, do

    • for j in range 0 to 31, do

      • res := res + c[(2^j) - x]

    • c[x] := c[x] + 1

  • return res

Example

Let us see the following implementation to get better understanding

from collections import Counter
def solve(nums):
   res, c = 0, Counter()
   for x in nums:
      for j in range(32):
         res += c[(1 << j) - x]
      c[x] += 1
   return res

nums = [1, 2, 6, 3, 5]
print(solve(nums))

Input

[1, 2, 6, 3, 5]

Output

3
Updated on: 2021-10-12T11:31:22+05:30

302 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements