The Wayback Machine - https://web.archive.org/web/20220325142610/https://www.geeksforgeeks.org/count-of-pairs-with-bitwise-xor-value-greater-than-its-bitwise-and-value/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count of pairs with bitwise XOR value greater than its bitwise AND value

  • Last Updated : 25 Mar, 2022

Given an array arr that contains N positive Integers. Find the count of all possible pairs whose bitwise XOR value is greater than bitwise AND value

Examples:

Input : arr[]={ 12, 4, 15}
Output:  2
Explanation: 12 ^ 4 = 8, 12 & 4 = 4. so 12 ^ 4 > 12 & 4
                       4 ^ 15 = 11,   4 & 15 = 4. so 4 ^ 15  > 4 & 15 . 
So, above two are valid pairs { 12, 4 }, {4, 15}  .

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

 

Approach: Refer to the below idea for the approach to solve this problem:

We know that, for an array of length N, there will be a total (N*(N-1))/2 pairs. 

Therefore check for every pair, and increase count by one if a pair satisfy the given condition in the question. 

Follow the below steps to solve this problem:

  • Check for every pair whether there bit wise XOR value is greater than bit wise AND or not.
  • If yes then increase the count
  • Return the count.

Below is the Implementation of the above approach: 

C++




// C++ program to Count number of pairs
// whose bit wise XOR value is greater
// than bit wise AND value
  
#include <bits/stdc++.h>
using namespace std;
  
// Function that return count of pairs
// whose bitwise xor >= bitwise
long long valid_pairs(int arr[], int N)
{
    long long cnt = 0;
    // check for all possible pairs
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N; j++) {
            if ((arr[i] ^ arr[j]) >= (arr[i] & arr[j]))
                cnt++;
        }
    }
  
    return cnt;
}
  
// Driver Code
int main()
{
    int N = 3;
    int arr[] = { 12, 4, 15 };
    cout << valid_pairs(arr, N);
}
Output
2

Time Complexity: O(N*N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!