Count of pairs with bitwise XOR value greater than its bitwise AND value
Last Updated :
28 Oct, 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 their 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++
#include <bits/stdc++.h>
using namespace std;
long long valid_pairs( int arr[], int N)
{
long long cnt = 0;
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;
}
int main()
{
int N = 3;
int arr[] = { 12, 4, 15 };
cout << valid_pairs(arr, N);
}
|
Java
import java.io.*;
class GFG
{
public static long valid_pairs( int arr[], int N)
{
long cnt = 0 ;
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;
}
public static void main(String[] args)
{
int N = 3 ;
int arr[] = { 12 , 4 , 15 };
System.out.print(valid_pairs(arr, N));
}
}
|
Python3
def valid_pairs(arr, N):
cnt = 0
for i in range ( 0 , N):
for j in range (i + 1 , N):
if ((arr[i] ^ arr[j]) > = (arr[i] & arr[j])):
cnt + = 1
return cnt
if __name__ = = "__main__" :
N = 3
arr = [ 12 , 4 , 15 ]
print (valid_pairs(arr, N))
|
C#
using System;
class GFG {
public static long valid_pairs( int [] arr, int N)
{
long cnt = 0;
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;
}
public static void Main( string [] args)
{
int N = 3;
int [] arr = { 12, 4, 15 };
Console.Write(valid_pairs(arr, N));
}
}
|
Javascript
<script>
function valid_pairs(arr, N) {
let cnt = 0;
for (let i = 0; i < N; i++) {
for (let j = i + 1; j < N; j++) {
if ((arr[i] ^ arr[j]) >= (arr[i] & arr[j]))
cnt++;
}
}
return cnt;
}
let N = 3;
let arr = [12, 4, 15];
document.write(valid_pairs(arr, N));
</script>
|
Time Complexity: O(N*N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...