# Maximize count of pairs whose Bitwise AND exceeds Bitwise XOR by replacing such pairs with their Bitwise AND

• Difficulty Level : Medium
• Last Updated : 12 May, 2021

Given an array arr[] consisting of N positive integers, replace pairs of array elements whose Bitwise AND exceeds Bitwise XOR values by their Bitwise AND value. Finally, count the maximum number of such pairs that can be generated from the array.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {12, 9, 15, 7}
Output: 2
Explanation:
Step 1: Select the pair {12, 15} and replace the pair by their Bitwise AND (= 12). The array arr[] modifies to {12, 9, 7}.
Step 2: Replace the pair {12, 9} by their Bitwise AND (= 8). Therefore, the array arr[] modifies to {8, 7}.
Therefore, the maximum number of such pairs is 2.

Input: arr[] = {2, 6, 12, 18, 9}
Output: 1

Naive Approach: The simplest approach to solve this problem is to generate all possible pairs and select a pair having Bitwise AND greater than their Bitwise XOR . Replace the pair and insert their Bitwise AND. Repeat the above process until no such pairs are found. Print the count of such pairs obtained.
Time Complexity: O(N3)
Auxiliary Space: O(1)

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

• A number having its most significant bit at the ith position can only form a pair with other numbers having MSB at the ith position.
• The total count of numbers having their MSB at the ith position decreases by one if one of these pairs is selected.
• Thus, the total pairs that can be formed at the ith position are the total count of numbers having MB at ith position decreased by 1.

Follow the steps below to solve the problem:

• Initialize a Map, say freq, to store the count of numbers having MSB at respective bit positions.
• Traverse the array and for each array element arr[i], find the MSB of arr[i] and increment the count of MSB in the freq by 1.
• Initialize a variable, say pairs, to store the count of total pairs.
• Traverse the map and update pairs as pairs += (freq[i] – 1).
• After completing the above steps, print the value of pairs as the result.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to count the number of``// pairs whose Bitwise AND is``// greater than the Bitwise XOR``int` `countPairs(``int` `arr[], ``int` `N)``{``    ``// Stores the frequency of``    ``// MSB of array elements``    ``unordered_map<``int``, ``int``> freq;` `    ``// Traverse the array``    ``for` `(``int` `i = 0; i < N; i++) {` `        ``// Increment count of numbers``        ``// having MSB at log(arr[i])``        ``freq[log2(arr[i])]++;``    ``}` `    ``// Stores total number of pairs``    ``int` `pairs = 0;` `    ``// Traverse the Map``    ``for` `(``auto` `i : freq) {``        ``pairs += i.second - 1;``    ``}` `    ``// Return total count of pairs``    ``return` `pairs;``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 12, 9, 15, 7 };``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);``    ``cout << countPairs(arr, N);` `    ``return` `0;``}`

## Java

 `// C# program for the above approach``import` `java.util.*;``class` `GFG {` `  ``// Function to count the number of``  ``// pairs whose Bitwise AND is``  ``// greater than the Bitwise XOR``  ``static` `int` `countPairs(``int``[] arr, ``int` `N)``  ``{` `    ``// Stores the frequency of``    ``// MSB of array elements``    ``HashMap freq``      ``= ``new` `HashMap();` `    ``// Traverse the array``    ``for` `(``int` `i = ``0``; i < N; i++) {` `      ``// Increment count of numbers``      ``// having MSB at log(arr[i])``      ``if` `(freq.containsKey((``int``)(Math.log(arr[i]))))``        ``freq.put((``int``)(Math.log(arr[i])),``                 ``(``int``)(Math.log(arr[i])) + ``1``);``      ``else``        ``freq.put((``int``)(Math.log(arr[i])), ``1``);``    ``}` `    ``// Stores total number of pairs``    ``int` `pairs = ``0``;` `    ``// Traverse the Map``    ``for` `(Map.Entry item :``         ``freq.entrySet())` `    ``{``      ``pairs += item.getValue() - ``1``;``    ``}` `    ``// Return total count of pairs``    ``return` `pairs;``  ``}` `  ``// Driver Code``  ``public` `static` `void` `main(String[] args)``  ``{``    ``int``[] arr = { ``12``, ``9``, ``15``, ``7` `};``    ``int` `N = arr.length;``    ``System.out.println(countPairs(arr, N));``  ``}``}` `// This code is contributed by ukasp.`

## Python3

 `# Python3 program for the above approach``from` `math ``import` `log2` `# Function to count the number of``# pairs whose Bitwise AND is``# greater than the Bitwise XOR``def` `countPairs(arr, N):``  ` `    ``# Stores the frequency of``    ``# MSB of array elements``    ``freq ``=` `{}` `    ``# Traverse the array``    ``for` `i ``in` `range``(N):` `        ``# Increment count of numbers``        ``# having MSB at log(arr[i])``        ``x ``=` `int``(log2(arr[i]))``        ``freq[x] ``=` `freq.get(x, ``0``) ``+` `1` `    ``# Stores total number of pairs``    ``pairs ``=` `0` `    ``# Traverse the Map``    ``for` `i ``in` `freq:``        ``pairs ``+``=` `freq[i] ``-` `1` `    ``# Return total count of pairs``    ``return` `pairs` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``arr ``=` `[``12``, ``9``, ``15``, ``7``]``    ``N ``=` `len``(arr)``    ``print``(countPairs(arr, N))` `    ``# This code is contributed by mohit kumar 29.`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;``class` `GFG``{` `// Function to count the number of``// pairs whose Bitwise AND is``// greater than the Bitwise XOR``static` `int` `countPairs(``int` `[]arr, ``int` `N)``{``  ` `    ``// Stores the frequency of``    ``// MSB of array elements``    ``Dictionary<``int``,``int``> freq = ``new` `Dictionary<``int``,``int``>();` `    ``// Traverse the array``    ``for` `(``int` `i = 0; i < N; i++)``    ``{` `        ``// Increment count of numbers``        ``// having MSB at log(arr[i])``        ``if``(freq.ContainsKey((``int``)(Math.Log(Convert.ToDouble(arr[i]),2.0))))``         ``freq[(``int``)(Math.Log(Convert.ToDouble(arr[i]),2.0))]++;``        ``else``          ``freq[(``int``)(Math.Log(Convert.ToDouble(arr[i]),2.0))] = 1;``    ``}` `    ``// Stores total number of pairs``    ``int` `pairs = 0;` `    ``// Traverse the Map``    ``foreach``(``var` `item ``in` `freq)``    ``{``        ``pairs += item.Value - 1;``    ``}` `    ``// Return total count of pairs``    ``return` `pairs;``}` `// Driver Code``public` `static` `void` `Main()``{``    ``int` `[]arr = { 12, 9, 15, 7 };``    ``int` `N =  arr.Length;``    ``Console.WriteLine(countPairs(arr, N));``}``}` `// This code is contributed by SURENDRA_GANGWAR.`

## Javascript

 ``
Output:
`2`

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

My Personal Notes arrow_drop_up