Given an array A[] of n integers, find out the number of ordered pairs such that Ai&Aj is zero, where 0<=(i,j)<n. Consider (i, j) and (j, i) to be different.
Constraints: 
1<=n<=104 
1<=Ai<=104
Examples:
Input : A[] = {3, 4, 2}
Output : 4
Explanation : The pairs are (3, 4) and (4, 2) which are 
counted as 2 as (4, 3) and (2, 4) are considered different. 
Input : A[]={5, 4, 1, 6}
Output : 4 
Explanation : (4, 1), (1, 4), (6, 1) and (1, 6) are the pairs
Simple approach: A simple approach is to check for all possible pairs and count the number of ordered pairs whose bitwise & returns 0.
Below is the implementation of the above idea:
C++
| // CPP program to calculate the number// of ordered pairs such that their bitwise// and is zero#include <bits/stdc++.h>usingnamespacestd;// Naive function to count the number// of ordered pairs such that their// bitwise and is 0intcountPairs(inta[], intn){    intcount = 0;    // check for all possible pairs    for(inti = 0; i < n; i++) {        for(intj = i + 1; j < n; j++)            if((a[i] & a[j]) == 0)                // add 2 as (i, j) and (j, i) are                 // considered different                count += 2;     }    returncount;}// Driver Codeintmain(){    inta[] = { 3, 4, 2 };    intn = sizeof(a) / sizeof(a[0]);        cout << countPairs(a, n);        return0;} | 
Java
| // Java program to calculate the number// of ordered pairs such that their bitwise// and is zeroclassGFG {        // Naive function to count the number    // of ordered pairs such that their    // bitwise and is 0    staticintcountPairs(inta[], intn)    {        intcount = 0;        // check for all possible pairs        for(inti = 0; i < n; i++) {            for(intj = i + 1; j < n; j++)                if((a[i] & a[j]) == 0)                    // add 2 as (i, j) and (j, i) are                    // considered different                    count += 2;        }        returncount;    }    // Driver Code    publicstaticvoidmain(String arg[])    {        inta[] = { 3, 4, 2};        intn = a.length;        System.out.print(countPairs(a, n));    }}// This code is contributed by Anant Agarwal. | 
Python3
| # Python3 program to calculate the number# of ordered pairs such that their# bitwise and is zero# Naive function to count the number# of ordered pairs such that their# bitwise and is 0defcountPairs(a, n):    count =0    # check for all possible pairs    fori inrange(0, n):        forj inrange(i +1, n):            if(a[i] & a[j]) ==0:                # add 2 as (i, j) and (j, i) are                 # considered different                count +=2    returncount# Driver Codea =[ 3, 4, 2]n =len(a) print(countPairs(a, n)) # This code is contributed# by Shreyanshi Arun. | 
C#
| // C# program to calculate the number// of ordered pairs such that their // bitwise and is zerousingSystem;classGFG {        // Naive function to count the number    // of ordered pairs such that their    // bitwise and is 0    staticintcountPairs(int[]a, intn)    {        intcount = 0;        // check for all possible pairs        for(inti = 0; i < n; i++)         {            for(intj = i + 1; j < n; j++)                if((a[i] & a[j]) == 0)                    // add 2 as (i, j) and (j, i)                     // arev considered different                    count += 2;        }        returncount;    }    // Driver Code    publicstaticvoidMain()    {        int[]a = { 3, 4, 2 };        intn = a.Length;        Console.Write(countPairs(a, n));    }}// This code is contributed by nitin mittal. | 
PHP
| <?php// PHP program to calculate the number// of ordered pairs such that their // bitwise and is zero// Naive function to count the number// of ordered pairs such that their// bitwise and is 0functioncountPairs($a, $n){    $count= 0;    // check for all possible pairs    for($i= 0; $i< $n; $i++)     {        for($j= $i+ 1; $j< $n; $j++)            if(($a[$i] & $a[$j]) == 0)                // add 2 as (i, j) and (j, i) are                 // considered different                $count+= 2;     }    return$count;}// Driver Code{    $a= array(3, 4, 2);    $n= sizeof($a) / sizeof($a[0]);     echocountPairs($a, $n);     return0;}// This code is contributed by nitin mittal | 
JavaScript
| <script>    // JavaScript program to calculate the number    // of ordered pairs such that their bitwise    // and is zero    // Naive function to count the number    // of ordered pairs such that their    // bitwise and is 0    const countPairs = (a, n) => {        let count = 0;        // check for all possible pairs        for(let i = 0; i < n; i++) {            for(let j = i + 1; j < n; j++)                if((a[i] & a[j]) == 0)                    // add 2 as (i, j) and (j, i) are                    // considered different                    count += 2;        }        returncount;    }    // Driver Code    let a = [3, 4, 2];    let n = a.length;    document.write(countPairs(a, n));    // This code is contributed by rakeshsahni</script>?> | 
4
Time Complexity: O(n2)
Auxiliary Space: O(1)
Efficient approach: An efficient approach is to use Sum over Subsets Dynamic Programming method and count the number of ordered pairs. In the SOS DP we find out the pairs whose bitwise & returned 0. Here we need to count the number of pairs. 
Some key observations are the constraints, the maximum that an array element can be is 104. Calculating the mask up to (1<<15) will give us our answer. Use hashing to count the occurrence of every element. If the last bit is OFF, then relating to SOS dp, we will have a base case since there is only one possibility of OFF bit. 
dp[mask][0] = freq(mask)
If the last bit is set ON, then we will have the base case as:
dp[mask][0] = freq(mask) + freq(mask^1)
We add freq(mask^1) to add the other possibility of OFF bit. 
Iterate over N=15 bits, which is the maximum possible.
Let’s consider the i-th bit to be 0, then no subset can differ from the mask in the i-th bit as it would mean that the numbers will have a 1 at i-th bit where the mask has a 0 which would mean that it is not a subset of the mask. Thus we conclude that the numbers now differ in the first (i-1) bits only. Hence, 
DP(mask, i) = DP(mask, i-1)
Now the second case, if the i-th bit is 1, it can be divided into two non-intersecting sets. One containing numbers with i-th bit as 1 and differing from mask in the next (i-1) bits. Second containing numbers with ith bit as 0 and differing from mask
(2i) in next (i-1) bits. Hence,
DP(mask, i) = DP(mask, i-1) + DP(mask
2i, i-1).
DP[mask][i] stores the number of subsets of mask which differ from mask only in first i bits. Iterate for all array elements, and for every array element add the number of subsets (dp[ ( ( 1<<N ) – 1 ) ^ a[i] ][ N ]) to the number of pairs. N = maximum number of bits.
Explanation of addition of dp[ ( ( 1<<N ) – 1 ) ^ a[i] ][N] to the number of pairs: Take an example of A[i] being 5, which is 101 in binary. For better understanding, assume N=3 in this case, therefore, the reverse of 101 will be 010 which on applying bitwise & gives 0. So (1<<3) gives 1000 which on subtraction from 1 gives 111. 111
 101 gives 010 which is the reversed bit.So dp[((1<<N)-1)^a[i]][N] will have the number of subsets that returns 0 on applying bitwise & operator.
Below is the implementation of the above idea:
C++
| // CPP program to calculate the number// of ordered pairs such that their bitwise// and is zero#include <bits/stdc++.h>usingnamespacestd;constintN = 15;// efficient function to count pairslonglongcountPairs(inta[], intn){    // stores the frequency of each number    unordered_map<int, int> hash;    longlongdp[1 << N][N + 1];        memset(dp, 0, sizeof(dp)); // initialize 0 to all    // count the frequency of every element    for(inti = 0; i < n; ++i)        hash[a[i]] += 1;    // iterate for all possible values that a[i] can be    for(longlongmask = 0; mask < (1 << N); ++mask) {        // if the last bit is ON        if(mask & 1)            dp[mask][0] = hash[mask] + hash[mask ^ 1];        else// is the last bit is OFF            dp[mask][0] = hash[mask];        // iterate till n        for(inti = 1; i <= N; ++i) {            // if mask's ith bit is set            if(mask & (1 << i))            {                dp[mask][i] = dp[mask][i - 1] +                         dp[mask ^ (1 << i)][i - 1];            }                else// if mask's ith bit is not set                dp[mask][i] = dp[mask][i - 1];        }    }    longlongans = 0;    // iterate for all the array element    // and count the number of pairs    for(inti = 0; i < n; i++)        ans += dp[((1 << N) - 1) ^ a[i]][N];    // return answer    returnans;}// Driver Codeintmain(){    inta[] = { 5, 4, 1, 6 };    intn = sizeof(a) / sizeof(a[0]);    cout << countPairs(a, n);    return0;} | 
Java
| // Java program to calculate // the number of ordered pairs // such that their bitwise // and is zero importjava.util.*;classGFG{    staticintN = 15;   // Efficient function to count pairs publicstaticintcountPairs(inta[],                              intn) {   // Stores the frequency of   // each number   HashMap<Integer,           Integer> hash = newHashMap<>();  intdp[][] = newint[1<< N][N + 1];   // Initialize 0 to all     // Count the frequency   // of every element   for(inti = 0; i < n; ++i)   {    if(hash.containsKey(a[i]))    {      hash.replace(a[i],       hash.get(a[i]) + 1);    }    else    {      hash.put(a[i], 1);    }  }  // Iterate for all possible   // values that a[i] can be   for(intmask = 0;            mask < (1<< N); ++mask)   {    // If the last bit is ON     if((mask & 1) != 0)     {      if(hash.containsKey(mask))      {        dp[mask][0] = hash.get(mask);      }      if(hash.containsKey(mask ^ 1))      {        dp[mask][0] += hash.get(mask ^ 1);      }    }    else    {      // is the last bit is OFF       if(hash.containsKey(mask))      {        dp[mask][0] = hash.get(mask);        }    }     // Iterate till n     for(inti = 1; i <= N; ++i)     {       // If mask's ith bit is set       if((mask & (1<< i)) != 0)       {         dp[mask][i] = dp[mask][i - 1] +                       dp[mask ^ (1<< i)][i - 1];       }           else      {        // If mask's ith bit is not set         dp[mask][i] = dp[mask][i - 1];       }     }   }   intans = 0;   // Iterate for all the   // array element and   // count the number of pairs   for(inti = 0; i < n; i++)   {    ans += dp[((1<< N) - 1) ^ a[i]][N];   }  // return answer   returnans; } // Driver code    publicstaticvoidmain(String[] args) {  inta[] = {5, 4, 1, 6};   intn = a.length;   System.out.print(countPairs(a, n)); }}// This code is contributed by divyeshrabadiya07 | 
Python3
| # Python program to calculate the number# of ordered pairs such that their bitwise# and is zeroN =15# efficient function to count pairsdefcountPairs(a, n):    # stores the frequency of each number    Hash={}        # initialize 0 to all    dp =[[0fori inrange(N +1)] forj inrange(1<< N)]    # count the frequency of every element    fori inrange(n):        ifa[i] notinHash:            Hash[a[i]] =1        else:            Hash[a[i]] +=1    # iterate for all possible values that a[i] can be    mask =0    while(mask < (1<< N)):        ifmask notinHash:            Hash[mask] =0        # if the last bit is ON        if(mask & 1):            dp[mask][0] =Hash[mask] +Hash[mask ^ 1]                    else:    # is the last bit is OFF            dp[mask][0] =Hash[mask]        # iterate till n        fori inrange(1, N +1):            # if mask's ith bit is set            if(mask & (1<< i)):                dp[mask][i] =dp[mask][i -1] +dp[mask ^ (1<< i)][i -1]                            else:    # if mask's ith bit is not set                dp[mask][i] =dp[mask][i -1]        mask +=1    ans =0        # iterate for all the array element    # and count the number of pairs    fori inrange(n):        ans +=dp[((1<< N) -1) ^ a[i]][N]            # return answer    returnans# Driver Codea =[5, 4, 1, 6]n =len(a)print(countPairs(a, n))# This code is contributed by avanitrachhadiya2155 | 
C#
| // C# program to calculate // the number of ordered pairs // such that their bitwise // and is zero usingSystem;usingSystem.Collections.Generic;classGFG {        staticintN = 15;        // Efficient function to count pairs     staticintcountPairs(int[] a, intn)     {       // Stores the frequency of       // each number       Dictionary<int, int> hash = newDictionary<int, int>();           int[, ] dp = newint[1 << N, N + 1];            // Initialize 0 to all              // Count the frequency       // of every element       for(inti = 0; i < n; ++i)       {        if(hash.ContainsKey(a[i]))        {          hash[a[i]] += 1;        }        else        {          hash.Add(a[i], 1);        }      }           // Iterate for all possible       // values that a[i] can be       for(intmask = 0;                mask < (1 << N); ++mask)       {        // If the last bit is ON         if((mask & 1) != 0)         {          if(hash.ContainsKey(mask))          {            dp[mask, 0] = hash[mask];          }          if(hash.ContainsKey(mask ^ 1))          {            dp[mask, 0] += hash[mask ^ 1];          }        }        else        {          // is the last bit is OFF           if(hash.ContainsKey(mask))          {            dp[mask, 0] = hash[mask];            }        }              // Iterate till n         for(inti = 1; i <= N; ++i)         {                     // If mask's ith bit is set           if((mask & (1 << i)) != 0)           {             dp[mask, i] = dp[mask, i - 1] +                           dp[mask ^ (1 << i), i - 1];           }               else          {                        // If mask's ith bit is not set             dp[mask, i] = dp[mask, i - 1];           }         }       }            intans = 0;            // Iterate for all the       // array element and       // count the number of pairs       for(inti = 0; i < n; i++)       {        ans += dp[((1 << N) - 1) ^ a[i], N];       }           // return answer       returnans;     }      // Driver code  staticvoidMain()   {      int[] a = {5, 4, 1, 6};       intn = a.Length;       Console.WriteLine(countPairs(a, n));   }}// This code is contributed by divyesh072019 | 
Javascript
| <script>// JavaScript program to calculate the number// of ordered pairs such that their bitwise// and is zeroconst N = 15;// efficient function to count pairsfunctioncountPairs(a, n){    // stores the frequency of each number    let hash = newMap();    let dp = newArray((1 << N));    for(let i = 0; i < (1 << N); i++) {        dp[i] = newArray(N+1).fill(0); // initialize 0 to all    }        // count the frequency of every element    for(let i = 0; i < n; ++i){              if(hash.has(a[i])){            hash.set(a[i], hash.get(a[i]) + 1);        }        else{            hash.set(a[i], 1);        }    }            // iterate for all possible values that a[i] can be    for(let mask = 0; mask < (1 << N); mask++) {        // console.log(mask);        // if the last bit is ON        if(mask & 1){                dp[mask][0] = ((hash.get(mask) != undefined) ? hash.get(mask): 0) + ((hash.get((mask ^ 1)) != undefined) ? hash.get((mask^1)): 0);        }        else{            // is the last bit is OFF            dp[mask][0] = hash.get(mask) != undefined ? hash.get(mask) : 0;        }                     // iterate till n        for(let i = 1; i <= N; i++) {            // if mask's ith bit is set            if(mask & (1 << i)){                dp[mask][i] = dp[mask][i - 1] +  dp[mask ^ (1 << i)][i - 1];            }                else{                // if mask's ith bit is not set                dp[mask][i] = dp[mask][i - 1];            }        }    }    let ans = 0;    // iterate for all the array element    // and count the number of pairs    for(let i = 0; i < n; i++){        ans = ans + dp[((1 << N) - 1) ^ a[i]][N];    }            // return answer    returnans;}// Driver Codelet a = [ 5, 4, 1, 6 ];let n = a.lengthdocument.write(countPairs(a, n));// The code is contributed by Gautam goel</script> | 
4
Time Complexity: O(N*2N) where N=15 which is a maximum number of bits possible, since Amax=104.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

 
                                    








