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: 2
Explanation:
Pair (5, 4): Bitwise XOR of 5 and 4 is 1. Remove this pair and add their Bitwise OR (= 5) into the array. Therefore, the modified array is {5, 7, 2}.
Pair (5, 2): Bitwise XOR of 5 and 2 is 7. Remove this pair and add their Bitwise OR (= 7) into the array. Therefore, the modified array is {7, 7}.
Therefore, the count of such pairs that can be removed is 2.
Input: arr[] = {2, 4, 6}
Output: 0
Approach: The given problem can be solved based on the following observations:
Therefore, the idea is to find the count of even elements present in the given array. If the count of even elements is N, then 0 moves are required. Otherwise, print the value of count as the resultant count of pairs required to be removed.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void countPairs( int arr[], int N)
{
int even = 0;
for ( int i = 0; i < N; i++) {
if (arr[i] % 2 == 0)
even++;
}
if (N - even >= 1) {
cout << even;
return ;
}
cout << 0;
}
int main()
{
int arr[] = { 5, 4, 7, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
countPairs(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG{
static void countPairs( int arr[], int N)
{
int even = 0 ;
for ( int i = 0 ; i < N; i++)
{
if (arr[i] % 2 == 0 )
even++;
}
if (N - even >= 1 )
{
System.out.println(even);
return ;
}
System.out.println( 0 );
}
public static void main(String[] args)
{
int arr[] = { 5 , 4 , 7 , 2 };
int N = arr.length;
countPairs(arr, N);
}
}
|
Python3
def countPairs(arr, N):
even = 0
for i in range (N):
if (arr[i] % 2 = = 0 ):
even + = 1
if (N - even > = 1 ):
print (even)
return
print ( 0 )
if __name__ = = "__main__" :
arr = [ 5 , 4 , 7 , 2 ]
N = len (arr)
countPairs(arr, N)
|
C#
using System;
class GFG{
static void countPairs( int [] arr, int N)
{
int even = 0;
for ( int i = 0; i < N; i++)
{
if (arr[i] % 2 == 0)
even++;
}
if (N - even >= 1)
{
Console.WriteLine(even);
return ;
}
Console.WriteLine(0);
}
static void Main()
{
int [] arr = { 5, 4, 7, 2 };
int N = arr.Length;
countPairs(arr, N);
}
}
|
Javascript
<script>
function countPairs(arr, N)
{
let even = 0;
for (let i = 0; i < N; i++) {
if (arr[i] % 2 == 0)
even++;
}
if (N - even >= 1) {
document.write(even);
return ;
}
document.write(0);
}
let arr = [ 5, 4, 7, 2 ];
let N = arr.length;
countPairs(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
06 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...