Rearrange array to make Bitwise XOR of similar indexed elements of two arrays is same

Given two arrays A[] and B[] consisting of N integers (N is odd), the task is to rearrange array B[] such that for each 1 ≤ i ≤ N, Bitwise XOR of A[i] and B[i] is the same. If no such rearrangement is possible, print “-1”. Otherwise, print the rearrangement.

Examples:

Input: A[] = {1, 2, 3, 4, 5}, B[] = {5, 4, 3, 2, 1}
Output: {1, 2, 3, 4, 5}
Explanation:
Rearranging the array B[] to {1, 2, 3, 4, 5}, Bitwise XOR between every corresponding pair of array elements is same i.e., 0.

Input: A[] = {14, 21, 33, 49, 53}, B[] = {54, 50, 34, 22, 14}
Output: -1

Naive Approach: The simplest approach is to generate all possible arrangements of array B[] and print that combinations of the array whose Bitwise XOR with corresponding elements is the same. 



Time Complexity: O(N!)
Auxiliary Space: O(1)

Efficient Approach: The idea is to use the commutative property of Bitwise XOR. Below are the steps:

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to rearrange the array
// B[] such that A[i] ^ B[i] is same
// for each element
vector<int> rearrangeArray(
    vector<int>& A, vector<int>& B, int N)
{
    // Store frequency of elements
    map<int, int> m;
 
    // Stores xor value
    int xor_value = 0;
 
    for (int i = 0; i < N; i++) {
 
        // Taking xor of all the
        // values of both arrays
        xor_value ^= A[i];
        xor_value ^= B[i];
 
        // Store frequency of B[]
        m[B[i]]++;
    }
 
    for (int i = 0; i < N; i++) {
 
        // Find the array B[] after
        // rearrangement
        B[i] = A[i] ^ xor_value;
 
        // If the updated value is
        // present then decrement
        // its frequency
        if (m[B[i]]) {
            m[B[i]]--;
        }
 
        // Otherwise return empty vector
        else
            return vector<int>{};
    }
 
    return B;
}
 
// Utility function to rearrange the
// array B[] such that A[i] ^ B[i]
// is same for each element
void rearrangeArrayUtil(
    vector<int>& A, vector<int>& B, int N)
{
    // Store rearranged array B
    vector<int> ans
        = rearrangeArray(A, B, N);
 
    // If rearrangement possible
    if (ans.size()) {
        for (auto x : ans) {
            cout << x << " ";
        }
    }
 
    // Otherwise return -1
    else {
        cout << "-1";
    }
}
 
// Driver Code
int main()
{
    // Given vector A
    vector<int> A = { 13, 21, 33, 49, 53 };
 
    // Given vector B
    vector<int> B = { 54, 50, 34, 22, 14 };
 
    // Size of the vector
    int N = (int)A.size();
 
    // Function Call
    rearrangeArrayUtil(A, B, N);
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to rearrange the array
// B[] such that A[i] ^ B[i] is same
// for each element
static ArrayList<Integer> rearrangeArray(
       ArrayList<Integer> A,
       ArrayList<Integer> B, int N)
{
     
    // Store frequency of elements
    HashMap<Integer,
            Integer> m = new HashMap<Integer,
                                     Integer>();
 
    // Stores xor value
    int xor_value = 0;
 
    for(int i = 0; i < N; i++)
    {
         
        // Taking xor of all the
        // values of both arrays
        xor_value ^= A.get(i);
        xor_value ^= B.get(i);
 
        // Store frequency of B[]
        m.put(B.get(i),
              m.getOrDefault(B.get(i) + 1, 0));
    }
 
    for(int i = 0; i < N; i++)
    {
         
        // Find the array B[] after
        // rearrangement
        B.set(i, A.get(i) ^ xor_value);
 
        // If the updated value is
        // present then decrement
        // its frequency
        if (m.getOrDefault(B.get(i), -1) != -1)
        {
            m.put(B.get(i),
                  m.getOrDefault(B.get(i), 0) - 1);
        }
 
        // Otherwise return empty vector
        else
            return (new ArrayList<Integer>());
    }
    return B;
}
 
// Utility function to rearrange the
// array B[] such that A[i] ^ B[i]
// is same for each element
static void rearrangeArrayUtil(ArrayList<Integer> A,
                               ArrayList<Integer> B, int N)
{
     
    // Store rearranged array B
    ArrayList<Integer> ans = rearrangeArray(A, B, N);
 
    // If rearrangement possible
    if (ans.size() != 0)
    {
        for(int i = 0; i < ans.size(); i++)
        {
            System.out.print(ans.get(i) + " ");
        }
    }
 
    // Otherwise return -1
    else
    {
        System.out.println("-1");
    }
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given vector A
    ArrayList<Integer> A = new ArrayList<Integer>(
        Arrays.asList(13, 21, 33, 49, 53));
 
    // Given vector B
    ArrayList<Integer> B = new ArrayList<Integer>(
        Arrays.asList(54, 50, 34, 22, 14));
 
    // Size of the vector
    int N = (int)A.size();
 
    // Function Call
    rearrangeArrayUtil(A, B, N);
}
}
 
// This code is contributed by akhilsaini
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to rearrange the array
# B[] such that A[i] ^ B[i] is same
# for each element
def rearrangeArray(A, B, N):
   
  # Store frequency of elements
  m = {}
 
  # Stores xor value
  xor_value = 0
 
  for i in range(0, N):
     
    # Taking xor of all the
    # values of both arrays
    xor_value ^= A[i]
    xor_value ^= B[i]
 
    # Store frequency of B[]
    if B[i] in m:
      m[B[i]] = m[B[i]] + 1
    else:
      m[B[i]] = 1
     
  for i in range(0, N):
     
    # Find the array B[] after
    # rearrangement
    B[i] = A[i] ^ xor_value
 
    # If the updated value is
    # present then decrement
    # its frequency
    if B[i] in m:
      m[B[i]] = m[B[i]] - 1
       
    # Otherwise return empty vector
    else:
      X = []
      return X
 
  return B
 
# Utility function to rearrange the
# array B[] such that A[i] ^ B[i]
# is same for each element
def rearrangeArrayUtil(A, B, N):
   
  # Store rearranged array B
  ans = rearrangeArray(A, B, N)
   
  # If rearrangement possible
  if (len(ans) > 0):
     for x in ans:
        print(x, end = ' ')
         
  # Otherwise return -1
  else:
    print("-1")
     
# Driver Code
if __name__ == '__main__':
   
  # Given vector A
  A = [ 13, 21, 33, 49, 53 ]
 
  # Given vector B
  B = [ 54, 50, 34, 22, 14 ]
 
  # Size of the vector
  N = len(A)
 
  # Function Call
  rearrangeArrayUtil(A, B, N)
   
# This code is contributed by akhilsaini
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
 
// Function to rearrange the array
// B[] such that A[i] ^ B[i] is same
// for each element
static ArrayList rearrangeArray(ArrayList A,
                                ArrayList B, int N)
{
     
    // Store frequency of elements
    Dictionary<int,
               int> m = new Dictionary<int,
                                       int>();
 
    // Stores xor value
    int xor_value = 0;
 
    for(int i = 0; i < N; i++)
    {
         
        // Taking xor of all the
        // values of both arrays
        xor_value ^= (int)A[i];
        xor_value ^= (int)B[i];
 
        // Store frequency of B[]
        if (!m.ContainsKey((int)B[i]))
            m.Add((int)B[i], 1);
        else
            m[(int)B[i]] = m[(int)B[i]] + 1;
    }
 
    for(int i = 0; i < N; i++)
    {
         
        // Find the array B[] after
        // rearrangement
        B[i] = (int)A[i] ^ xor_value;
 
        // If the updated value is
        // present then decrement
        // its frequency
        if (m.ContainsKey((int)B[i]))
        {
            m[(int)B[i]]--;
        }
 
        // Otherwise return empty vector
        else
            return (new ArrayList());
    }
    return B;
}
 
// Utility function to rearrange the
// array B[] such that A[i] ^ B[i]
// is same for each element
static void rearrangeArrayUtil(ArrayList A,
                               ArrayList B,
                               int N)
{
     
    // Store rearranged array B
    ArrayList ans = rearrangeArray(A, B, N);
 
    // If rearrangement possible
    if (ans.Count != 0)
    {
        for(int i = 0; i < ans.Count; i++)
        {
            Console.Write(ans[i] + " ");
        }
    }
     
    // Otherwise return -1
    else
    {
        Console.WriteLine("-1");
    }
}
 
// Driver Code
public static void Main()
{
     
    // Given vector A
    ArrayList A = new ArrayList{ 13, 21, 33, 49, 53 };
 
    // Given vector B
    ArrayList B = new ArrayList{ 54, 50, 34, 22, 14 };
 
    // Size of the vector
    int N = A.Count;
 
    // Function Call
    rearrangeArrayUtil(A, B, N);
}
}
 
// This code is contributed by akhilsaini
chevron_right

Output: 
14 22 34 50 54



 

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




Article Tags :