Maximize count of pairs whose Bitwise AND exceeds Bitwise XOR by replacing such pairs with their Bitwise AND
Last Updated :
14 Mar, 2023
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));
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>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Maximize count of pairs whose bitwise XOR is even by replacing such pairs with their Bitwise XOR
Given an array arr[] of size N, the task is to replace a pair of array elements whose Bitwise XOR is even by their Bitwise XOR. Repeat the above step as long as possible. Finally, print the count of such operations performed on the array Examples: Input: arr[] = { 4, 6, 1, 3 }Output: 3Explanation:St
11 min read
Maximize sum of squares of array elements possible by replacing pairs with their Bitwise AND and Bitwise OR
Given an array arr[] consisting of N integers, the task is to find the maximum sum of the squares of array elements possible from the given array by performing the following operations:Select any pair of array elements (arr[i], arr[j])Replace arr[i] by arr[i] AND arr[j]Replace arr[j] by arr[i] OR ar
14 min read
Count pairs with odd Bitwise XOR that can be removed and replaced by their Bitwise OR
Given an array arr[] consisting of N integers, the task is to count the number of pairs whose Bitwise XOR is odd, that can be removed and replaced by their Bitwise OR values until no such pair exists in the array. Examples: Input: arr[] = {5, 4, 7, 2}Output: 2Explanation:Pair (5, 4): Bitwise XOR of
5 min read
Total pairs in an array such that the bitwise AND, bitwise OR and bitwise XOR of LSB is 1
Given an array arr[] of size N. The task is to find the number of pairs (arr[i], arr[j]) as cntAND, cntOR, and cntXOR such that: cntAND: Count of pairs where bitwise AND of least significant bits is 1.cntOR: Count of pairs where bitwise OR of least significant bits is 1.cntXOR: Count of pairs where
7 min read
Count pairs with Bitwise XOR greater than both the elements of the pair
Given an array arr[] of size N, the task is to count the number of pairs whose Bitwise XOR is greater than both the elements in the pair. Examples: Input: arr[] = {2, 4, 3}Output: 2Explanation: There are only 2 pairs whose Bitwise XOR is greater than both the elements in the pair:1) (2, 4): Bitwise
10 min read
Count of pairs with bitwise XOR value greater than its bitwise AND value | Set 2
Given an array arr that contains N positive Integers. Find the count of all possible pairs whose bit wise XOR value is greater than bit wise AND value Examples: Input : arr[]={ 12, 4 , 15}Output: 2Explanation: 12 ^ 4 = 8 , 12 & 4 = 4 . so 12 ^ 4 > 12 & 4 4 ^ 15 = 11, 4 & 15 = 4. so 4
6 min read
Count pairs with bitwise XOR exceeding bitwise AND from a given array
Given an array, arr[] of size N, the task is to count the number of pairs from the given array such that the bitwise AND(&) of each pair is less than its bitwise XOR(^). Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 8Explanation: Pairs that satisfy the given conditions are: (1 & 2) < (
10 min read
Minimize Array Sum by replacing pairs with (X, Y) keeping their bitwise OR same
Given an array arr[] of size N. Find the minimum sum of the array after performing given operations any number of times: Select two different indices i, j (1 ⤠i < j ⤠N),Replace arr[i] and arr[j] with X and Y respectively (X, Y>0), such that arr[i] | arr[j] = X | Y, where | denotes the bitwis
5 min read
Find a pair of numbers with set bit count as at most that of N and whose Bitwise XOR is N
Given a positive integer N, the task is to find the pair of integers (X, Y) such that the Bitwise XOR of X and Y is N and X * Y is maximum where the count of bits in X and Y is less than or equal to N. Examples: Input: N = 10Output: 13 7Explanation: The case where X = 13 and Y = 7 is the most optima
6 min read
Calculate Bitwise OR of two integers from their given Bitwise AND and Bitwise XOR values
Given two integers X and Y, representing Bitwise XOR and Bitwise AND of two positive integers, the task is to calculate the Bitwise OR value of those two positive integers.Examples:Input: X = 5, Y = 2 Output: 7 Explanation: If A and B are two positive integers such that A ^ B = 5, A & B = 2, the
7 min read