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++
#include <bits/stdc++.h>
using namespace std;
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;
}
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#
using System;
using System.Collections.Generic;
class GFG {
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;
}
public static void Main()
{
List< int > arr = new List< int >(){ 2, 6, 12, 18, 9 };
Console.Write(countPairs(arr));
}
}
|
Javascript
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;
}
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++
#include <bits/stdc++.h>
using namespace std;
int countPairs( int arr[], int N)
{
unordered_map< int , int > freq;
for ( int i = 0; i < N; i++) {
freq[log2(arr[i])]++;
}
int pairs = 0;
for ( auto i : freq) {
pairs += i.second - 1;
}
return pairs;
}
int main()
{
int arr[] = { 12, 9, 15, 7 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << countPairs(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int countPairs( int [] arr, int N)
{
HashMap<Integer, Integer> freq
= new HashMap<Integer, Integer>();
for ( int i = 0 ; i < N; 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 );
}
int pairs = 0 ;
for (Map.Entry<Integer, Integer> item :
freq.entrySet())
{
pairs += item.getValue() - 1 ;
}
return pairs;
}
public static void main(String[] args)
{
int [] arr = { 12 , 9 , 15 , 7 };
int N = arr.length;
System.out.println(countPairs(arr, N));
}
}
|
Python3
from math import log2
def countPairs(arr, N):
freq = {}
for i in range (N):
x = int (log2(arr[i]))
freq[x] = freq.get(x, 0 ) + 1
pairs = 0
for i in freq:
pairs + = freq[i] - 1
return pairs
if __name__ = = '__main__' :
arr = [ 12 , 9 , 15 , 7 ]
N = len (arr)
print (countPairs(arr, N))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int countPairs( int []arr, int N)
{
Dictionary< int , int > freq = new Dictionary< int , int >();
for ( int i = 0; i < N; 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;
}
int pairs = 0;
foreach ( var item in freq)
{
pairs += item.Value - 1;
}
return pairs;
}
public static void Main()
{
int []arr = { 12, 9, 15, 7 };
int N = arr.Length;
Console.WriteLine(countPairs(arr, N));
}
}
|
Javascript
<script>
function countPairs(arr, N)
{
var freq = new Map();
for ( var i = 0; i < N; 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);
}
}
var pairs = 0;
freq.forEach((value,key) => {
pairs += value - 1;
});
return pairs;
}
var arr = [12, 9, 15, 7 ];
var N = arr.length;
document.write( countPairs(arr, N));
</script>
|
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 geeks!
Last Updated :
14 Mar, 2023
Like Article
Save Article