Open In App

Maximize count of pairs whose bitwise XOR is even by replacing such pairs with their Bitwise XOR

Improve
Improve
Like Article
Like
Save
Share
Report

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: 3
Explanation:
Step 1: Remove the pair (4, 6) and replace them by their XOR value (= 2) in the array. Therefore, the array arr[] modifies to {2, 1, 3}.
Step 2: Remove the pair (1, 3) and replace them by their XOR value (= 2) in the array, modifies the array as arr[] = {2, 2}.
At last select the pair (2, 2) and then remove the pair and insert the xor of 2 and 2 in the array which modifies the array as arr[] ={0}.
Now no other pair can be chosen therefore 3 is the maximum number of pairs whose Xor is even.

Input: arr[ ] = { 1, 2, 3, 4, 5 }
Output: 3

Naive Approach: The simplest approach to solve this problem is to find all possible pairs of the array and for each pair, check if their Bitwise XOR is even or not. If found to be true, then increment the count of pairs and remove both the elements from the array and add their XOR to the array. Repeat the above steps until no more pairs can be selected. Print the count of operations performed. 

C++




#include <iostream>
#include <vector>
using namespace std;
 
// Function to check if the bitwise XOR of two elements is
// even
bool isEvenXOR(int a, int b) { return !((a ^ b) & 1); }
 
int replacePair(vector<int>& arr)
{
    int operations = 0;
    bool replaced = true;
 
    while (replaced) {
        replaced = false;
        int first, second;
 
        for (int i = 0; i < arr.size() - 1; i++) {
            for (int j = i + 1; j < arr.size(); j++) {
 
                if (isEvenXOR(arr[i], arr[j])) {
                    first = i;
                    second = j;
                    replaced = true;
                    operations++;
                    break;
                }
            }
            if (replaced)
                break;
        }
        if (replaced) {
            int xorr = arr[first] ^ arr[second];
            arr.erase(arr.begin() + first);
            arr.erase(arr.begin() + second - 1);
            arr.push_back(xorr);
        }
    }
    return operations;
}
 
int main()
{
    vector<int> arr = { 1,2,3,4,5 };
    int operations = replacePair(arr);
    cout << "Operations performed: " << operations << endl;
    for (int i = 0; i < arr.size(); i++) {
        cout << arr[i] << " ";
    }
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
class Main {
    // Function to check if the bitwise XOR of two elements is
    // even
    public static boolean isEvenXOR(int a, int b) { return (a ^ b) % 2 == 0; }
 
    public static int replacePair(List<Integer> arr) {
        int operations = 0;
        boolean replaced = true;
 
        while (replaced) {
            replaced = false;
            int first = 0, second = 0;
 
            for (int i = 0; i < arr.size() - 1; i++) {
                for (int j = i + 1; j < arr.size(); j++) {
 
                    if (isEvenXOR(arr.get(i), arr.get(j))) {
                        first = i;
                        second = j;
                        replaced = true;
                        operations++;
                        break;
                    }
                }
                if (replaced)
                    break;
            }
            if (replaced) {
                int xorr = arr.get(first) ^ arr.get(second);
                arr.remove(first);
                arr.remove(second - 1);
                arr.add(xorr);
            }
        }
        return operations;
    }
 
    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        arr.add(5);
        int operations = replacePair(arr);
        System.out.println("Operations performed: " + operations);
        for (int i = 0; i < arr.size(); i++) {
            System.out.print(arr.get(i) + " ");
        }
    }
}


Python3




def is_even_xor(a, b):
    return (a ^ b) % 2 == 0
 
def replace_pair(arr):
    operations = 0
    replaced = True
 
    while replaced:
        replaced = False
        first = 0
        second = 0
 
        for i in range(len(arr) - 1):
            for j in range(i + 1, len(arr)):
 
                if is_even_xor(arr[i], arr[j]):
                    first = i
                    second = j
                    replaced = True
                    operations += 1
                    break
            if replaced:
                break
        if replaced:
            xorr = arr[first] ^ arr[second]
            arr.pop(first)
            arr.pop(second - 1)
            arr.append(xorr)
    return operations
 
arr = [1, 2, 3, 4, 5]
operations = replace_pair(arr)
print("Operations performed:", operations)
for i in range(len(arr)):
    print(arr[i], end=" ")


C#




using System;
using System.Collections.Generic;
 
class GFG
{
    // Function to check if the bitwise XOR of two elements is
    // even
    static bool isEvenXOR(int a, int b)
    {
        return ((a ^ b) & 1)==0;
    }
     
    static int replacePair(List<int> arr)
    {
        int operations = 0;
        bool replaced = true;
     
        while (replaced) {
            replaced = false;
            int first=0, second=0;
     
            for (int i = 0; i < arr.Count - 1; i++) {
                for (int j = i + 1; j < arr.Count; j++) {
     
                    if (isEvenXOR(arr[i], arr[j])) {
                        first = i;
                        second = j;
                        replaced = true;
                        operations++;
                        break;
                    }
                }
                if (replaced)
                    break;
            }
            if (replaced) {
                int xorr = arr[first] ^ arr[second];
                arr.Remove(arr[first]);
                arr.Remove(arr[second - 1]);
                arr.Add(xorr);
            }
        }
        return operations;
    }
     
    static void Main(string[] args)
    {
        List<int> arr = new List<int>{ 1,2,3,4,5 };
        int operations = replacePair(arr);
        Console.WriteLine("Operations performed: " + operations);
        for (int i = 0; i < arr.Count; i++) {
            Console.Write(arr[i]+" ");
        }
    }
}


Javascript




// JavaScript code to implement above approach
 
// Function to check if the bitwise XOR of two elements is
// even
function isEvenXOR(a, b) {
  return (a ^ b) % 2 === 0;
}
 
function replacePair(arr) {
  let operations = 0;
  let replaced = true;
 
  while (replaced) {
    replaced = false;
    let first = 0,
      second = 0;
 
    for (let i = 0; i < arr.length - 1; i++) {
      for (let j = i + 1; j < arr.length; j++) {
        if (isEvenXOR(arr[i], arr[j])) {
          first = i;
          second = j;
          replaced = true;
          operations++;
          break;
        }
      }
      if (replaced) break;
    }
    if (replaced) {
      let xorr = arr[first] ^ arr[second];
      arr.splice(first, 1);
      arr.splice(second - 1, 1);
      arr.push(xorr);
    }
  }
  return operations;
}
 
// Driver code
let arr = [1, 2, 3, 4, 5];
let operations = replacePair(arr);
console.log("Operations performed: " + operations);
console.log(arr);
// this code is contributed by devendra salunke


Output

Operations performed: 3
5 4 

Time Complexity: O(N2), as we have to use nested loops to traverse N3 times.
Auxiliary Space: O(1), as we are not using any extra space.

Efficient Approach: The above approach can be optimized based on the following observations:

  • Even ^ Even = Even
  • Odd ^ Odd = Even
  • The total number of pairs that can be formed from only odd numbers satisfying the conditions is odd / 2.
  • The total numbers of pairs that can be formed from only even numbers satisfying the conditions is even – 1.

Follow the steps below to solve the problem:

  1. Traverse the array.
  2. Count the frequency of odd numbers and store it in a variable, say odd.
  3. The total number of pairs with even XOR that can be formed from all the odd array elements is floor(odd / 2).
  4. Deleting the formed pairs in the above step and replacing them with their XOR values respectively, increases the count of even elements by floor(odd / 2).
  5. Finally, print the count of pairs that can be formed with even XOR as (N – odd + odd/2 -1) + odd / 2.

Below is the implementation of the above approach:

C++




// C++ program to implement the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to maximize the count
// of pairs with even XOR possible
// in an array by given operations
int countPairs(int arr[], int N)
{
    // Stores count of odd
    // array elements
    int odd = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // If arr[i] is odd
        if (arr[i] & 1)
            odd++;
    }
 
    // Stores the total number
    // of even pairs
    int ans = (N - odd + odd / 2
               - 1)
              + odd / 2;
 
    return ans;
}
 
// Driver Code
int main()
{
    // Input
    int arr[] = { 4, 6, 1, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call to count the number
    // of pairs whose XOR is even
    cout << countPairs(arr, N);
 
    return 0;
}


C




// C program to implement the above approach
#include <stdio.h>
 
// Function to maximize the count
// of pairs with even XOR possible
// in an array by given operations
int countPairs(int arr[], int N)
{
  // Stores count of odd
  // array elements
  int odd = 0;
 
  // Traverse the array
  for (int i = 0; i < N; i++) {
 
    // If arr[i] is odd
    if (arr[i] & 1)
      odd++;
  }
 
  // Stores the total number
  // of even pairs
  int ans = (N - odd + odd / 2
             - 1)
    + odd / 2;
 
  return ans;
}
 
// Driver Code
int main()
{
  // Input
  int arr[] = { 4, 6, 1, 3 };
  int N = sizeof(arr) / sizeof(arr[0]);
 
  // Function call to count the number
  // of pairs whose XOR is even
  printf("%d\n", countPairs(arr, N));
 
  return 0;
}
 
// This code is contributed by phalashi.


Python3




# Python3 program to implement the above approach
 
# Function to maximize the count
# of pairs with even XOR possible
# in an array by given operations
def countPairs(arr, N):
   
    # Stores count of odd
    # array elements
    odd = 0
 
    # Traverse the array
    for i in range(N):
 
        # If arr[i] is odd
        if (arr[i] & 1):
            odd += 1
 
    # Stores the total number
    # of even pairs
    ans = (N - odd + odd // 2 - 1) + odd // 2
 
    return ans
 
# Driver Code
if __name__ == '__main__':
   
  # Input
    arr =[4, 6, 1, 3]
    N = len(arr)
 
    # Function call to count the number
    # of pairs whose XOR is even
    print (countPairs(arr, N))
 
    # This code is contributed by mohit kumar 29.


Java




// Java program to implement the above approach
public class GFG
{
 
  // Function to maximize the count
  // of pairs with even XOR possible
  // in an array by given operations
  static int countPairs(int []arr, int N)
  {
 
    // Stores count of odd
    // array elements
    int odd = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
 
      // If arr[i] is odd
      if ((arr[i] & 1)!=0)
        odd++;
    }
 
    // Stores the total number
    // of even pairs
    int ans = (N - odd + odd / 2
               - 1)
      + odd / 2;
 
    return ans;
  }
 
  // Driver Code
  public static void main(String args[])
  {
 
    // Input
    int []arr = { 4, 6, 1, 3 };
    int N = arr.length;
 
    // Function call to count the number
    // of pairs whose XOR is even
    System.out.println(countPairs(arr, N));
  }
}
 
// This code is contributed by AnkThon.


C#




// C# program to implement the above approach
using System;
class GFG
{
 
// Function to maximize the count
// of pairs with even XOR possible
// in an array by given operations
static int countPairs(int []arr, int N)
{
   
    // Stores count of odd
    // array elements
    int odd = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
 
        // If arr[i] is odd
        if ((arr[i] & 1)!=0)
            odd++;
    }
 
    // Stores the total number
    // of even pairs
    int ans = (N - odd + odd / 2
               - 1)
              + odd / 2;
 
    return ans;
}
 
// Driver Code
public static void Main()
{
   
    // Input
    int []arr = { 4, 6, 1, 3 };
    int N = arr.Length;
 
    // Function call to count the number
    // of pairs whose XOR is even
    Console.Write(countPairs(arr, N));
}
}
 
// This code is contributed by SURENDRA_GANGWAR.


Javascript




<script>
// JavaScript program to implement the above approach
 
// Function to maximize the count
// of pairs with even XOR possible
// in an array by given operations
function countPairs(arr, N)
{
    // Stores count of odd
    // array elements
    let odd = 0;
 
    // Traverse the array
    for (let i = 0; i < N; i++) {
 
        // If arr[i] is odd
        if (arr[i] & 1)
            odd++;
    }
 
    // Stores the total number
    // of even pairs
    let ans = (N - odd + Math.floor(odd / 2) - 1) + Math.floor(odd / 2);
 
    return ans;
}
 
// Driver Code
 
    // Input
    let arr = [ 4, 6, 1, 3 ];
    let N = arr.length;
 
    // Function call to count the number
    // of pairs whose XOR is even
    document.write(countPairs(arr, N));
 
// This code is contributed by Surbhi Tyagi.
 
</script>


Output: 

3

 

Time Complexity: O(N), as we are using a loop to traverse N times.
Auxiliary Space: O(1), as we are not using any extra space.



Last Updated : 16 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads