Count of pairs from Array with sum equal to twice their bitwise AND

Given an array arr[], the task is to count the pairs in the array with sum equal to twice their bitwise AND, i.e., A + B = 2 * (A \& B)
Examples:

Input: arr[] = {1, 1, 3, 4, 4, 5, 7, 8}
Output: 2
Explaination:
Pairs with sum equal to twice their bitwise AND:
{(1, 1), (4, 4)}

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

Naive Approach: A simple solution is to iterate over every possible pair and check that if the sum of the pair is equal to the twice the Bit-wise AND of the pair. If the pair have the equal sum and bitwise AND then increment the count of such pairs by 1.

Efficient Approach: The idea is to use the relation between the sum and the bitwise AND. That is –



A + B = (A \^ B) + 2 * (A \& B)

In this for equal sum and the bitwise AND, the value of the Bitwise XOR of the pair should be equal to 0. We know that the Bitwise XOR of any two pairs is equal to 0 only if they are equal to each other. Therefore, if X is the frequency of the element. Then increment the count of pairs by ^{X}C_{2}.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the pairs
// with equal sum and twice the
// bitwise AND of the pairs
  
#include <bits/stdc++.h>
  
using namespace std;
  
// Map to store the
// occurrence of
// elements of array
map<int, int> mp;
  
// Function to find the pairs
// with equal sum and twice the
// bitwise AND of the pairs
int find_pairs(int ar[], int n)
{
    int ans = 0;
  
    // Loop to find the frequency
    // of elements of array
    for (int i = 0; i < n; i++) {
        mp[ar[i]]++;
    }
  
    // Function to find the count
    // such pairs in the array
    for (auto i : mp) {
        int count = i.second;
        if (count > 1) {
  
            // if an element occurs more
            // than once then the answer
            // will by incremented
            // by nC2 times
            ans += ((count
                     * (count - 1))
                    / 2);
        }
    }
    return ans;
}
  
// Driver Code
int main()
{
    int ar[]
        = { 1, 2, 3, 3, 4,
            5, 5, 7, 8 };
    int arr_size = (sizeof(ar)
                    / sizeof(ar[0]));
  
    // Function Call
    cout << find_pairs(ar, arr_size);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find the pairs
// with equal sum and twice the
// bitwise AND of the pairs
import java.util.*;
  
class GFG{
  
// Map to store the
// occurrence of
// elements of array
static HashMap<Integer, 
               Integer> mp = new HashMap<Integer,
                                         Integer>();
  
// Function to find the pairs
// with equal sum and twice the
// bitwise AND of the pairs
static int find_pairs(int arr[], int n)
{
    int ans = 0;
  
    // Loop to find the frequency
    // of elements of array
    for(int i = 0; i < n; i++)
    {
       if(mp.containsKey(arr[i]))
       {
           mp.put(arr[i], mp.get(arr[i]) + 1);
       }
       else
       {
           mp.put(arr[i], 1);
       }
    }
      
    // Function to find the count
    // such pairs in the array
    for(Map.Entry<Integer, Integer> i:mp.entrySet())
    {
       int count = i.getValue();
       if (count > 1)
       {
  
           // If an element occurs more
           // than once then the answer
           // will by incremented
           // by nC2 times
           ans += ((count * (count - 1)) / 2);
       }
    }
    return ans;
}
  
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 3, 3, 4,
                  5, 5, 7, 8 };
    int arr_size = arr.length;
  
    // Function Call
    System.out.print(find_pairs(arr, arr_size));
}
}
  
// This code is contributed by amal kumar choubey

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to find the 
# pairs with equal sum and twice the
# bitwise AND of the pairs
from collections import defaultdict 
  
# Map to store the occurrence 
# of elements of array
mp = defaultdict(int)
  
# Function to find the pairs
# with equal sum and twice the
# bitwise AND of the pairs
def find_pairs(arr, n):
  
    ans = 0
  
    # Loop to find the frequency
    # of elements of array
    for i in range(n):
        mp[arr[i]] += 1
  
    # Function to find the count
    # such pairs in the array
    for i in mp.values():
        count = i
        if (count > 1):
  
            # If an element occurs more
            # than once then the answer
            # will by incremented
            # by nC2 times
            ans += ((count * (count - 1)) // 2)
      
    return ans
  
# Driver Code
if __name__ == "__main__":
  
    arr = [ 1, 2, 3, 3, 4,
            5, 5, 7, 8 ]
    arr_size = len(arr)
  
    # Function Call
    print(find_pairs(arr, arr_size))
  
# This code is contributed by chitranayal 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to find the pairs
// with equal sum and twice the
// bitwise AND of the pairs
using System;
using System.Collections.Generic;
  
class GFG{
  
// To store the occurrence 
// of elements of array
static Dictionary<int
                  int> mp = new Dictionary<int,
                                           int>();
  
// Function to find the pairs
// with equal sum and twice the
// bitwise AND of the pairs
static int find_pairs(int []arr, int n)
{
    int ans = 0;
  
    // Loop to find the frequency
    // of elements of array
    for(int i = 0; i < n; i++)
    {
       if(mp.ContainsKey(arr[i]))
       {
           mp[arr[i]] = mp[arr[i]] + 1;
       }
       else
       {
           mp.Add(arr[i], 1);
       }
    }
      
    // Function to find the count
    // such pairs in the array
    foreach(KeyValuePair<int, int> i in mp)
    {
       int count = i.Value;
       if (count > 1)
       {
             
           // If an element occurs more
           // than once then the answer
           // will by incremented
           // by nC2 times
           ans += ((count * (count - 1)) / 2);
       }
    }
    return ans;
}
  
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 1, 2, 3, 3, 4,
                  5, 5, 7, 8 };
    int arr_size = arr.Length;
  
    // Function Call
    Console.Write(find_pairs(arr, arr_size));
}
}
  
// This code is contributed by amal kumar choubey

chevron_right


Output:

2

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.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.