Sunday, December 29, 2024
Google search engine
HomeData Modelling & AIMaximize count of pairs whose Bitwise AND exceeds Bitwise XOR by replacing...

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 XOR
int 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 Code
int 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 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(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 XOR
function 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 Code
let arr = [ 2, 6, 12, 18, 9 ];
console.log(countPairs(arr));


Output

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 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[0]);
    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<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 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




<script>
 
// Javascript program for the above approach
 
// Function to count the number of
// pairs whose Bitwise AND is
// greater than the Bitwise XOR
function 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 Code
var arr = [12, 9, 15, 7 ];
var N = arr.length;
document.write( countPairs(arr, N));
 
</script>


Output

2

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!

RELATED ARTICLES

Most Popular

Recent Comments