Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmCount pairs with equal Bitwise AND and Bitwise OR value

Count pairs with equal Bitwise AND and Bitwise OR value

Given an array, arr[] of size N, the task is to count the number of unordered pairs such that Bitwise AND and Bitwise OR of each pair is equal.

Examples:

Input: arr[] = {1, 2, 1} 
Output:
Explanation: 
Bitwise AND value and Bitwise OR value all possible pairs are: 
Bitwise AND of the pair(arr[0], arr[1]) is (arr[0] & arr[1]) = (1 & 2) = 0 
Bitwise AND of the pair(arr[0], arr[1]) is (arr[0] | arr[1]) = (1 | 2) = 3 
Bitwise AND of the pair(arr[0], arr[2]) is (arr[0] & arr[2]) = (1 & 2) = 1 
Bitwise AND of the pair(arr[0], arr[1]) is (arr[0] | arr[1]) = (1 | 2) = 1 
Bitwise AND of the pair(arr[1], arr[2]) is (arr[1] & arr[2]) = (2 & 1) = 0 
Bitwise AND of the pair(arr[0], arr[1]) is arr[0] | arr[1] = (2 | 1) = 3 
Therefore, the required output is 1. 

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

Naive Approach: The simplest approach to solve the problem is to traverse the array and generate all possible pairs of the given array. For each pair, check if Bitwise And of the pair is equal to Bitwise OR of that pair or not. If found to be true, then increment the counter. Finally, print the value of the counter.

Efficient Approach: To optimize the above approach the idea is based on the following observations:

0 & 0 = 0 and 0 | 0 = 0 
0 & 1 = 0 and 0 | 1 = 1 
1 & 0 = 0 and 1 | 0 = 1 
1 & 1 = 1 and 1 | 1 = 1 
 

Therefore, If both the elements of a pair are equal, only then, bitwise AND(&) and Bitwise OR(|) of the pair becomes equal. 

Follow the steps below to solve the problem:

  • Initialize a variable, say cntPairs to store the count of pairs whose Bitwise AND(&) value and Bitwise OR(|) value is equal.
  • Create a map, say mp to store the frequency of all distinct elements of the given array.
  • Traverse the given array and store the frequency of all distinct elements of the given array in mp.
  • Traverse map and check if frequency, say freq is greater than 1 then update cntPairs += (freq * (freq – 1)) / 2.
  • Finally, print the value of cntPairs.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count pairs in an array
// whose bitwise AND equal to bitwise OR
int countPairs(int arr[], int N)
{
     
    // Store count of pairs whose
    // bitwise AND equal to bitwise OR
    int cntPairs = 0;
     
    // Stores frequency of
    // distinct elements of array
    map<int, int> mp;
     
    // Traverse the array
    for (int i = 0; i < N; i++) {
         
        // Increment the frequency
        // of arr[i]
        mp[arr[i]]++;
    }
     
    // Traverse map
    for (auto freq: mp) {
        cntPairs += (freq.second *
                   (freq.second - 1)) / 2;
    }
     
    return cntPairs;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 1, 2, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout<<countPairs(arr, N);
}


Java




// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to count pairs in an array
// whose bitwise AND equal to bitwise OR
static int countPairs(int[] arr, int N)
{
     
    // Store count of pairs whose
    // bitwise AND equal to bitwise OR
    int cntPairs = 0;
 
    // Stores frequency of
    // distinct elements of array
    HashMap<Integer, Integer> mp = new HashMap<>();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Increment the frequency
        // of arr[i]
        mp.put(arr[i],
               mp.getOrDefault(arr[i], 0) + 1);
    }
 
    // Traverse map
    for(Map.Entry<Integer, Integer> freq : mp.entrySet())
    {
        cntPairs += (freq.getValue() *
                    (freq.getValue() - 1)) / 2;
    }
 
    return cntPairs;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 2, 3, 1, 2, 2 };
    int N = arr.length;
     
    System.out.println(countPairs(arr, N));
}
}
 
// This code is contributed by akhilsaini


Python3




# Python3 program to implement
# the above approach
 
# Function to count pairs in an array
# whose bitwise AND equal to bitwise OR
def countPairs(arr, N):
     
    # Store count of pairs whose
    # bitwise AND equal to bitwise OR
    cntPairs = 0
 
    # Stores frequency of
    # distinct elements of array
    mp = {}
 
    # Traverse the array
    for i in range(0, N):
         
        # Increment the frequency
        # of arr[i]
        if arr[i] in mp:
            mp[arr[i]] = mp[arr[i]] + 1
        else:
            mp[arr[i]] = 1
 
    # Traverse map
    for freq in mp:
        cntPairs += int((mp[freq] *
                        (mp[freq] - 1)) / 2)
 
    return cntPairs
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ 1, 2, 3, 1, 2, 2 ]
    N = len(arr)
     
    print(countPairs(arr, N))
 
# This code is contributed by akhilsaini


C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count pairs in an array
// whose bitwise AND equal to bitwise OR
static int countPairs(int[] arr, int N)
{
     
    // Store count of pairs whose
    // bitwise AND equal to bitwise OR
    int cntPairs = 0;
 
    // Stores frequency of
    // distinct elements of array
    Dictionary<int,
               int> mp = new Dictionary<int,
                                        int>();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Increment the frequency
        // of arr[i]
        if (!mp.ContainsKey(arr[i]))
            mp.Add(arr[i], 1);
        else
            mp[arr[i]] = mp[arr[i]] + 1;
    }
 
    // Traverse map
    foreach(KeyValuePair<int, int> freq in mp)
    {
        cntPairs += (freq.Value *
                    (freq.Value - 1)) / 2;
    }
 
    return cntPairs;
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 2, 3, 1, 2, 2 };
    int N = arr.Length;
     
    Console.WriteLine(countPairs(arr, N));
}
}
 
// This code is contributed by akhilsaini


Javascript




<script>
  
// JavaScript program to implement
// the above approach
 
// Function to count pairs in an array
// whose bitwise AND equal to bitwise OR
function countPairs(arr, N)
{
     
    // Store count of pairs whose
    // bitwise AND equal to bitwise OR
    var cntPairs = 0;
     
    // Stores frequency of
    // distinct elements of array
    var mp = new Map();
     
    // Traverse the array
    for (var i = 0; i < N; i++) {
         
        // Increment the frequency
        // of arr[i]
        if(mp.has(arr[i]))
            mp.set(arr[i], mp.get(arr[i])+1)
        else
            mp.set(arr[i], 1);
    }
     
    // Traverse map
    mp.forEach((value, key) => {
         
        cntPairs += parseInt((value *
                   (value - 1)) / 2);
    });
     
    return cntPairs;
}
 
// Driver Code
var arr = [1, 2, 3, 1, 2, 2 ];
var N = arr.length;
document.write( countPairs(arr, N));
 
</script>


Output: 

4

 

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nango Kalahttps://www.kala.co.za
Experienced Support Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Microsoft Excel, Customer Service, Microsoft Word, Technical Support, and Microsoft Office. Strong information technology professional with a Microsoft Certificate Solutions Expert (Privet Cloud) focused in Information Technology from Broadband Collage Of Technology.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments