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

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:
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.
Follow the below steps to implement the above idea:
- Initialize cnt to 0.
- Start a while loop.
- Initialize flag to true.
- Iterate over the elements of the vector using a nested for loop.
- For each pair of elements (arr[i], arr[j]) where i < j, check if the Bitwise AND of the two numbers is greater than the Bitwise XOR of the two numbers.
- If the condition is true, remove the two elements from the vector using the erase function and insert the Bitwise AND of the two elements at the end of the vector using the push_back function.
- Set flag to false to indicate that a pair has been found.
- Increment cnt by 1.
- Break out of the inner loop.
- If flag is still true after iterating over all the elements of the vector, break out of the infinite loop.
- Return cnt as the output of the function.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to count the number of// pairs whose Bitwise AND is// greater than the Bitwise XORint countPairs(vector<int>& arr){Â
    int cnt = 0;Â
    while (true) {        bool flag = true;        for (int i = 0; i < arr.size(); i++) {            for (int j = i + 1; j < arr.size(); j++) {                if ((arr[j] & arr[i]) > (arr[j] ^ arr[i])) {                    arr.erase(arr.begin() + i);                    arr.erase(arr.begin() + j - 1);                    arr.push_back((arr[j] & arr[i]));                    flag = false;                    cnt++;                    break;                }            }            if (flag == false)                break;        }Â
        if (flag)            break;    }    return cnt;}Â
// Driver Codeint main(){Â Â Â Â vector<int> arr = { 2, 6, 12, 18, 9 };Â Â Â Â cout << countPairs(arr);Â
    return 0;} |
Java
import java.util.ArrayList;Â
class Main {Â
    public static int countPairs(ArrayList<Integer> arr)    {        int cnt = 0;Â
        while (true) {            boolean flag = true;            for (int i = 0; i < arr.size(); i++) {                for (int j = i + 1; j < arr.size(); j++) {                    if ((arr.get(j) & arr.get(i))                        > (arr.get(j) ^ arr.get(i))) {                        arr.remove(i);                        arr.remove(j - 1);                        arr.add((arr.get(j) & arr.get(i)));                        flag = false;                        cnt++;                        break;                    }                }                if (flag == false)                    break;            }Â
            if (flag)                break;        }        return cnt;    }Â
    public static void main(String[] args)    {        ArrayList<Integer> arr = new ArrayList<Integer>();        arr.add(2);        arr.add(6);        arr.add(12);        arr.add(18);        arr.add(9);        System.out.println(countPairs(arr));    }} |
Python3
from typing import ListÂ
def countPairs(arr: List[int]) -> int:    cnt = 0    while True:        flag = True        for i in range(len(arr)):            for j in range(i+1, len(arr)):                if (arr[j] & arr[i]) > (arr[j] ^ arr[i]):                    result = arr[j] & arr[i]                    del arr[i]                    del arr[j-1]                    arr.append(result)                    flag = False                    cnt += 1                    break            if flag == False:                break        if flag:            break    return cntÂ
arr = [2, 6, 12, 18, 9]print(countPairs(arr)) |
C#
// C# implementation of the above approachusing 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(List<int> arr)  {    int cnt = 0;    while (true)    {      bool flag = true;      for (int i = 0; i < arr.Count; i++)      {        for (int j = i + 1; j < arr.Count; j++)        {          if ((arr[j] & arr[i]) > (arr[j] ^ arr[i]))          {            int bitwiseOp = (arr[j] & arr[i]);            arr.RemoveAt(i);            j--;            arr.RemoveAt(j);            arr.Add(bitwiseOp);            flag = false;            cnt++;            break;          }        }        if (flag == false)          break;      }      if (flag)        break;    }    return cnt;  }Â
  // Driver Code  public static void Main()  {    List<int> arr = new List<int>(){ 2, 6, 12, 18, 9 };    Console.Write(countPairs(arr));  }   }Â
// This code is contributed by agrawalpoojaa976. |
Javascript
// Javascript program for the above approachÂ
// Function to count the number of// pairs whose Bitwise AND is// greater than the Bitwise XORfunction countPairs(arr){Â
    let cnt = 0;Â
    while (true) {        let flag = true;        for (let i = 0; i < arr.length; i++) {            for (let j = i + 1; j < arr.length; j++) {                if ((arr[j] & arr[i]) > (arr[j] ^ arr[i])) {                    delete arr[i];                    delete arr[j-1];                    arr.push((arr[j] & arr[i]));                    flag = false;                    cnt++;                    break;                }            }            if (flag == false)                break;        }Â
        if (flag)            break;    }    return cnt;}Â
// Driver Codelet arr = [ 2, 6, 12, 18, 9 ];console.log(countPairs(arr)); |
1
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 <bits/stdc++.h>using namespace std;Â
// Function to count the number of// pairs whose Bitwise AND is// greater than the Bitwise XORint 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 Codeint main(){Â Â Â Â int arr[] = { 12, 9, 15, 7 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â cout << countPairs(arr, N);Â
    return 0;} |
Java
// C# program for the above approachimport 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<Integer, Integer> freq      = new HashMap<Integer, Integer>();Â
    // 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<Integer, Integer> 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 approachfrom math import log2Â
# Function to count the number of# pairs whose Bitwise AND is# greater than the Bitwise XORdef 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 Codeif __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 approachusing System;using System.Collections.Generic;class GFG{Â
// Function to count the number of// pairs whose Bitwise AND is// greater than the Bitwise XORstatic 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 Codepublic 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
<script>Â
// Javascript program for the above approachÂ
// Function to count the number of// pairs whose Bitwise AND is// greater than the Bitwise XORfunction countPairs(arr, N){    // Stores the frequency of    // MSB of array elements    var freq = new Map();Â
    // Traverse the array    for (var i = 0; i < N; i++) {Â
        // Increment count of numbers        // having MSB at log(arr[i])        if(freq.has(parseInt(Math.log2(arr[i]))))        {            freq.set(parseInt(Math.log2(arr[i])), freq.get(parseInt(Math.log2(arr[i])))+1);        }        else        {            freq.set(parseInt(Math.log2(arr[i])), 1);        }    }Â
    // Stores total number of pairs    var pairs = 0;Â
    // Traverse the Map    freq.forEach((value,key) => {        pairs += value - 1;    });Â
    // Return total count of pairs    return pairs;}Â
// Driver Codevar arr = [12, 9, 15, 7 ];var N = arr.length;document.write( countPairs(arr, N));Â
</script> |
2
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



