Open In App

Count pairs in Array such that their bitwise XOR has Kth right bit set

Last Updated : 25 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N and an integer K, the task is to find the number of pairs in the array such that the Kth bit from the right of their bitwise XOR is set.

Examples:

Input: arr[] = {3, 13, 2, 9}, N = 4, K = 3
Output: 4
Explanation: The pairs that have the kth bit set in bitwise xor value are  {3, 13}, {3, 9}, {2, 13}, {2, 9}

Input: arr[] = {7, 6, 5, 3}, N = 4, K = 2
Output: 3
Explanation: The pairs that have a kth bit set in bitwise xor value are {7, 3}, {6, 3}, {5, 3}

Naive Approach:  The basic way to solve the problem is as follows:

The most basic way to solve this problem is to consider each possible pair of elements from the array and check whether the number formed from the bitwise xor of both elements has a kth bit set. 

C++




#include <iostream>
using namespace std;
 
int countPairs(int arr[], int n, int k) {
    int count = 0;
    for (int i = 0; i < n-1; i++) {
        for (int j = i+1; j < n; j++) {
            if ((arr[i]^arr[j]) & (1 << (k))) {
                count++;
            }
        }
    }
    return count;
}
 
int main() {
    // TestCase 1
    int arr1[] = { 3, 13, 2, 9 };
    int K = 1;
    int N = sizeof(arr1) / sizeof(arr1[0]);
 
    // Function Call
    cout << countPairs(arr1, N, K) << endl;
 
    // Testcase 2
    int arr2[] = { 7, 6, 5, 3 };
    K = 2;
    N = sizeof(arr2) / sizeof(arr2[0]);
 
    // Function Call
    cout << countPairs(arr2, N, K) << endl;
 
    return 0;
}


Java




import java.util.Arrays;
 
public class GFG {
   
      // Function to check kth bit
    public static int countPairs(int[] arr, int n, int k) {
        int count = 0;
        for (int i = 0; i < n-1; i++) {
            for (int j = i+1; j < n; j++) {
                  // Chekcing bit is set of not
                if (((arr[i]^arr[j]) & (1 << (k))) != 0) {
                    count++;
                }
            }
        }
          // Returning total pair
        return count;
    }
     
    public static void main(String[] args) {
        int[] arr1 = { 3, 13, 2, 9 };
        int K = 1;
        int N = arr1.length;
         
        System.out.println(countPairs(arr1, N, K));
         
        int[] arr2 = { 7, 6, 5, 3 };
        K = 2;
        N = arr2.length;
         
        System.out.println(countPairs(arr2, N, K));
    }
}


Python3




def countPairs(arr, n, k):
    count = 0
    for i in range(n-1):
        for j in range(i+1, n):
            if (arr[i]^arr[j]) & (1 << k):
                count += 1
    return count
 
# TestCase 1 
arr1 = [3, 13, 2, 9]
K = 1
N = len(arr1)
# Function Call
print(countPairs(arr1, N, K))
 
# Testcase 2
arr2 = [7, 6, 5, 3]
K = 2
N = len(arr2)
# Function Call
print(countPairs(arr2, N, K))


C#




using System;
 
public class GFG {
     
      // Function to check kth bit
    public static int countPairs(int[] arr, int n, int k) {
        int count = 0;
        for (int i = 0; i < n-1; i++) {
            for (int j = i+1; j < n; j++) {
                // Chekcing bit is set of not
                if (((arr[i]^arr[j]) & (1 << (k))) != 0) {
                    count++;
                }
            }
        }
         
          // Returning total pair
        return count;
    }
   
      // Driver code
    public static void Main(string[] args) {
        int[] arr1 = { 3, 13, 2, 9 };
        int K = 1;
        int N = arr1.Length;
        Console.WriteLine(countPairs(arr1, N, K));
        int[] arr2 = { 7, 6, 5, 3 };
        K = 2;
        N = arr2.Length;
        Console.WriteLine(countPairs(arr2, N, K));
    }
}


Javascript




function countPairs(arr, n, k) {
    let count = 0;
    for (let i = 0; i < n - 1; i++) {
        for (let j = i + 1; j < n; j++) {
            if ((arr[i] ^ arr[j]) & (1 << k)) {
                count += 1;
            }
        }
    }
    return count;
}
 
// TestCase 1
const arr1 = [3, 13, 2, 9];
const K = 1;
const N1 = arr1.length;
// Function Call
console.log(countPairs(arr1, N1, K));
 
// Testcase 2
const arr2 = [7, 6, 5, 3];
const K1 = 2;
const N = arr2.length;
// Function Call
console.log(countPairs(arr2, N, K1));


Output

4
3






Time Complexity: O(N2 * log(Max_ele)) where Max_ele is the largest element of the array.
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized based on the following idea:

Consider two numbers X and Y where X is having its Kth bit set. Only the following two scenarios can happen :

  • If Y also has Kth bit set then X^Y will have Kth bit unset.
  • If the Kth bit of Y is unset then X^Y will have the Kth bit set.

Follow the below-mentioned steps to implement the above approach:

  • Count the number of elements having Kth right bit set.
  • For each element arr[i] we know if it has Kth right bit set or not.
    • If the Kth right bit is set in arr[i] then take a count of all those elements that have bit unset at the Kth position from right.
    • If the Kth right bit is unset in arr[i] then consider all those elements that have set the bit at the Kth position from right.
  • Ultimately, divide the final answer by 2 as the calculation considers each pair twice.

Below is the implementation of the above approach.

C++




// C++ implementation of above program
 
#include <bits/stdc++.h>
using namespace std;
 
int solve(int arr[], int n, int k)
{
    int bits[32];
 
    // Initialize an array to store the
    // count of elements having i'th bit set
    memset(bits, 0, sizeof(bits));
 
    // Count the number of elements that
    // have jth bit set
    for (int i = 0; i < n; i++) {
 
        for (int j = 0; j < 32; j++) {
 
            // check if jth bit is set or not
            if ((arr[i] & (1 << j)) > 0) {
                bits[j]++;
            }
        }
    }
 
    int ans = 0;
    for (int i = 0; i < n; i++) {
 
        // If kth bit is set for an element
        // then add all those numbers to the
        // answer for which kth bit is unset.
        if ((arr[i] & (1 << k)) > 0) {
            ans += (n - bits[k]);
        }
 
        // Else do the opposite
        else {
            ans += (bits[k]);
        }
    }
 
    // Since the above calculation considers
    // each pair twice we need to divide the
    // answer by 2
    ans = ans / 2;
 
    // Return the answer
    return ans;
}
 
// Driver Code
int main()
{
    // TestCase 1
    int arr1[] = { 3, 13, 2, 9 };
    int K = 1;
    int N = sizeof(arr1) / sizeof(arr1[0]);
 
    // Function Call
    cout << solve(arr1, N, K) << endl;
 
    // Testcase 2
    int arr2[] = { 7, 6, 5, 3 };
    K = 2;
    N = sizeof(arr2) / sizeof(arr2[0]);
 
    // Function Call
    cout << solve(arr2, N, K) << endl;
 
    return 0;
}


Java




// Java code for the above approach
import java.util.Arrays;
 
public class Main {
  public static int solve(int[] arr, int n, int k) {
    int[] bits = new int[32];
 
    // Initialize an array to store the
    // count of elements having i'th bit set
    Arrays.fill(bits, 0);
 
    // Count the number of elements that
    // have jth bit set
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < 32; j++) {
        // check if jth bit is set or not
        if ((arr[i] & (1 << j)) > 0) {
          bits[j]++;
        }
      }
    }
 
    int ans = 0;
    for (int i = 0; i < n; i++) {
      // If kth bit is set for an element
      // then add all those numbers to the
      // answer for which kth bit is unset.
      if ((arr[i] & (1 << k)) > 0) {
        ans += (n - bits[k]);
      }
      // Else do the opposite
      else {
        ans += (bits[k]);
      }
    }
 
    // Since the above calculation considers
    // each pair twice we need to divide the
    // answer by 2
    ans = ans / 2;
 
    // Return the answer
    return ans;
  }
 
  public static void main(String[] args) {
    // TestCase 1
    int[] arr1 = {3, 13, 2, 9};
    int K = 1;
    int N = arr1.length;
 
    // Function Call
    System.out.println(solve(arr1, N, K));
 
    // Testcase 2
    int[] arr2 = {7, 6, 5, 3};
    K = 2;
    N = arr2.length;
 
    // Function Call
    System.out.println(solve(arr2, N, K));
  }
}
 
// This code is contributed by lokeshpotta20.


Python3




# python implementation of above program
 
def solve(arr, n, k):
    # Initialize an array to store the
    # count of elements having i'th bit set
    bits = [0] * 32
     
    # Count the number of elements that
    # have jth bit set
     
    for i in range(n):
       
        for j in range(32):
             
           # check if jth bit is set or not
             
            if arr[i] & (1 << j) > 0:
                bits[j] += 1
 
    ans = 0
    for i in range(n):
       
        # If kth bit is set for an element
        # then add all those numbers to the
        # answer for which kth bit is unset.
        if arr[i] & (1 << k) > 0:
            ans += (n - bits[k])
        # Else do the opposite
         
        else:
            ans += bits[k]
 
    # Since the above calculation considers
    # each pair twice we need to divide the
    # answer by 2
    ans = ans // 2
 
    # Return the answer
    return ans
# Driver Code
 
# TestCase 1
arr1 = [3, 13, 2, 9]
K = 1
N = len(arr1)
 
# Function Call
print(solve(arr1, N, K))
 
# Testcase 2
arr2 = [7, 6, 5, 3]
K = 2
N = len(arr2)
 
# Function Call
print(solve(arr2, N, K))
#This code is contributed by rutikbhosale.


C#




// C# implementation of above program
 
using System;
 
class Gfg{
 
    static int solve(int[] arr, int n, int k)
    {
        int[] bits=new int[32];
     
        // Initialize an array to store the
        // count of elements having i'th bit set
        for(int i=0; i<32; i++)
            bits[i]=0;
 
        // Count the number of elements that
        // have jth bit set
        for (int i = 0; i < n; i++) {
     
            for (int j = 0; j < 32; j++) {
     
                // check if jth bit is set or not
                if ((arr[i] & (1 << j)) > 0) {
                    bits[j]++;
                }
            }
        }
     
        int ans = 0;
        for (int i = 0; i < n; i++) {
     
            // If kth bit is set for an element
            // then add all those numbers to the
            // answer for which kth bit is unset.
            if ((arr[i] & (1 << k)) > 0) {
                ans += (n - bits[k]);
            }
     
            // Else do the opposite
            else {
                ans += (bits[k]);
            }
        }
     
        // Since the above calculation considers
        // each pair twice we need to divide the
        // answer by 2
        ans = ans / 2;
     
        // Return the answer
        return ans;
    }
     
    // Driver Code
    public static void Main()
    {
        // TestCase 1
        int[] arr1 = { 3, 13, 2, 9 };
        int K = 1;
        int N = arr1.Length;
     
        // Function Call
        Console.WriteLine(solve(arr1, N, K));
     
        // Testcase 2
        int[] arr2 = { 7, 6, 5, 3 };
        K = 2;
        N = arr2.Length;
     
        // Function Call
        Console.WriteLine(solve(arr2, N, K));
     
    }
}


Javascript




// Javascript implementation of above program
 
function solve( arr,  n,  k)
{
    let bits=new Array(32).fill(0);
 
    // Initialize an array to store the
    // count of elements having i'th bit set
 
    // Count the number of elements that
    // have jth bit set
    for (let i = 0; i < n; i++) {
 
        for (let j = 0; j < 32; j++) {
 
            // check if jth bit is set or not
            if ((arr[i] & (1 << j)) > 0) {
                bits[j]++;
            }
        }
    }
 
    let ans = 0;
    for (let i = 0; i < n; i++) {
 
        // If kth bit is set for an element
        // then add all those numbers to the
        // answer for which kth bit is unset.
        if ((arr[i] & (1 << k)) > 0) {
            ans += (n - bits[k]);
        }
 
        // Else do the opposite
        else {
            ans += (bits[k]);
        }
    }
 
    // Since the above calculation considers
    // each pair twice we need to divide the
    // answer by 2
    ans = Math.floor(ans / 2);
 
    // Return the answer
    return ans;
}
 
// Driver Code
// TestCase 1
let arr1 = [ 3, 13, 2, 9 ];
let K = 1;
let N = arr1.length;
 
// Function Call
console.log(solve(arr1, N, K));
 
// Testcase 2
let arr2 = [ 7, 6, 5, 3 ];
K = 2;
N = arr2.length;
 
// Function Call
console.log(solve(arr2, N, K));
 
// This code is contributed by ratiagrawal.


Output

4
3





Time Complexity: O(N * log(Max_ele)) where Max_ele is the maximum value in the array
Auxiliary Space: O(1)

Related Articles:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads