Program to count indices pairs for which elements sum is power of 2 in Python

PythonServer Side ProgrammingProgramming

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
raja
Updated on 12-Oct-2021 11:31:22

Advertisements