Related Articles

# Number of pairs whose sum is a power of 2 | Set 2

• Difficulty Level : Medium
• Last Updated : 19 May, 2021

Given an array arr[] consisting of N integers, the task is to count the maximum number of pairs (arr[i], arr[j]) such that arr[i] + arr[j] is a power of 2.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {1, -1, 2, 3}
Output: 5
Explanation: (1, 1), (2, 2), (1, 3), (-1, 3), (-1, 2) are the valid pairs whose sum is power of 2.

Input: arr[] = {1, 1, 1}
Output: 6

Naive Approach: The simplest approach to solve the problem is to generate all possible pairs from a given array and for each pair, check if the sum of the pair is a power of 2 or not
Time Complexity: O(N2
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized using HashMap. Follow the steps below to solve the problem:

• Create a Map to store frequency of each element of the array arr[].
• Initialize a variable ans to store the count of pairs with sum equal to any power of 2.
• Traverse the range [0, 31] and generate all the powers of 2, i.e. 20 to 231.
• Traverse the given array for every power of 2 generated and check if map[key – arr[j]] exists or not, where key is equal to 2i.
• If found to be true, increase count by map[key – arr[j]], as pair(s) (arr[j], key – arr[j]) exists with sum equal to a power of 2.
• Finally, print count / 2 as the required answer.

Below is the implementation of the above approach:

## C++

 `// C++ program to implement``// the above approach` `#include ``using` `namespace` `std;` `// Function to count all pairs``// whose sum is a power of two``int` `countPair(``int` `arr[], ``int` `n)``{``    ``// Stores the frequency of``    ``// each element of the array``    ``map<``int``, ``int``> m;` `    ``// Update frequency of``    ``// array elements``    ``for` `(``int` `i = 0; i < n; i++)``        ``m[arr[i]]++;` `    ``// Stores count of``    ``// required pairs``    ``int` `ans = 0;` `    ``for` `(``int` `i = 0; i < 31; i++) {` `        ``// Current power of 2``        ``int` `key = ``pow``(2, i);` `        ``// Traverse the array``        ``for` `(``int` `j = 0; j < n; j++) {` `            ``int` `k = key - arr[j];` `            ``// If pair does not exist``            ``if` `(m.find(k) == m.end())``                ``continue``;` `            ``// Increment count of pairs``            ``else``                ``ans += m[k];` `            ``if` `(k == arr[j])``                ``ans++;``        ``}``    ``}` `    ``// Return the count of pairs``    ``return` `ans / 2;``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 1, 8, 2, 10, 6 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``cout << countPair(arr, n) << endl;` `    ``return` `0;``}`

## Java

 `// Java program to implement``// the above approach``import` `java.util.*;` `class` `GFG {``    ``// Function to count all pairs``    ``// whose sum is power of two``    ``static` `int` `countPair(``int``[] arr, ``int` `n)``    ``{``        ``// Stores the frequency of``        ``// each element of the array``        ``Map m``            ``= ``new` `HashMap<>();` `        ``// Update the frequency of``        ``// array elements``        ``for` `(``int` `i = ``0``; i < n; i++)``            ``m.put(arr[i], m.getOrDefault(``                            ``arr[i], ``0``)``                            ``+ ``1``);` `        ``// Stores the count of pairs``        ``int` `ans = ``0``;` `        ``// Generate powers of 2``        ``for` `(``int` `i = ``0``; i < ``31``; i++) {` `            ``// Generate current power of 2``            ``int` `key = (``int``)Math.pow(``2``, i);` `            ``// Traverse the array``            ``for` `(``int` `j = ``0``; j < arr.length;``                ``j++) {` `                ``int` `k = key - arr[j];` `                ``// Increase ans by m[k], if``                ``// pairs with sum 2^i exists``                ``ans += m.getOrDefault(k, ``0``);` `                ``// Increase ans again if k = arr[j]``                ``if` `(k == arr[j])``                    ``ans++;``            ``}``        ``}` `        ``// Return count of pairs``        ``return` `ans / ``2``;``    ``}` `    ``// Driver function``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int``[] arr = { ``1``, -``1``, ``2``, ``3` `};``        ``int` `n = arr.length;``        ``System.out.println(countPair(arr, n));``    ``}``}`

## Python3

 `# Python3 program to implement``# the above approach``from` `math ``import` `pow` `# Function to count all pairs``# whose sum is a power of two``def` `countPair(arr, n):``    ` `    ``# Stores the frequency of``    ``# each element of the array``    ``m ``=` `{}` `    ``# Update frequency of``    ``# array elements``    ``for` `i ``in` `range``(n):``        ``m[arr[i]] ``=` `m.get(arr[i], ``0``) ``+` `1` `    ``# Stores count of``    ``# required pairs``    ``ans ``=` `0` `    ``for` `i ``in` `range``(``31``):``        ` `        ``# Current power of 2``        ``key ``=` `int``(``pow``(``2``, i))` `        ``# Traverse the array``        ``for` `j ``in` `range``(n):``            ``k ``=` `key ``-` `arr[j]` `            ``# If pair does not exist``            ``if` `k ``not` `in` `m:``                ``continue` `            ``# Increment count of pairs``            ``else``:``                ``ans ``+``=` `m.get(k, ``0``)` `            ``if` `(k ``=``=` `arr[j]):``                ``ans ``+``=` `1` `    ``# Return the count of pairs``    ``return` `ans ``/``/` `2` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``arr ``=`  `[ ``1``, ``8``, ``2``, ``10``, ``6` `]``    ``n ``=` `len``(arr)``    ` `    ``print``(countPair(arr, n))` `# This code is contributed by SURENDRA_GANGWAR`

## Javascript

 ``

Output:

`5`

Time Complexity: O(NlogN)

Auxiliary Space: O(1)

My Personal Notes arrow_drop_up