Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Last Updated :
23 Jul, 2025
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal.
Examples:
Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}
Output: 5
Explanation:
Below are the possible arrangements:
- Rearrange the array B[] to {4, 7, 6}. Now, the Bitwise XOR of the same indexed elements are equal, i.e. 1 ^ 4 = 5, 2 ^ 7 = 5, 3 ^ 6 = 5.
After the rearrangements, required Bitwise XOR is 5.
Input: A[] = { 7, 8, 14 }, B[] = { 5, 12, 3 }
Output: 11
Explanation:
Below are the possible arrangements:
- Rearrange the array B[] to {12, 3, 5}. Now, the Bitwise XOR of the same indexed elements are equal, i.e. 7 ^ 12 = 11, 8 ^ 3 = 11, 14 ^ 5 = 11.
After the rearrangements, required Bitwise XOR is 11.
Naive Approach: The given problem can be solved based on the observation that the count of rearrangements can be at most N because any element in A[] can only be paired with N other integers in B[]. So, there are N candidate values for X. Now, simply XOR all the candidates with each element in A[] and check if B[] can be arranged in that order.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find all possible values
// of Bitwise XOR such after rearranging
// the array elements the Bitwise XOR
// value at corresponding indexes is same
void findPossibleValues(int A[], int B[],
int n)
{
// Sort the array B
sort(B, B + n);
int C[n];
// Stores all the possible values
// of the Bitwise XOR
set<int> numbers;
// Iterate over the range
for (int i = 0; i < n; i++) {
// Possible value of K
int candidate = A[0] ^ B[i];
// Array B for the considered
// value of K
for (int j = 0; j < n; j++) {
C[j] = A[j] ^ candidate;
}
sort(C, C + n);
bool flag = false;
// Verify if the considered value
// satisfies the condition or not
for (int j = 0; j < n; j++)
if (C[j] != B[j])
flag = true;
// Insert the possible Bitwise
// XOR value
if (!flag)
numbers.insert(candidate);
}
// Print all the values obtained
for (auto x : numbers) {
cout << x << " ";
}
}
// Driver Code
int main()
{
int A[] = { 7, 8, 14 };
int B[] = { 5, 12, 3 };
int N = sizeof(A) / sizeof(A[0]);
findPossibleValues(A, B, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Function to find all possible values
// of Bitwise XOR such after rearranging
// the array elements the Bitwise XOR
// value at corresponding indexes is same
static void findPossibleValues(int A[], int B[],
int n)
{
// Sort the array B
Arrays.sort(B);
int []C = new int[n];
// Stores all the possible values
// of the Bitwise XOR
HashSet<Integer> numbers = new HashSet<Integer>();
// Iterate over the range
for (int i = 0; i < n; i++) {
// Possible value of K
int candidate = A[0] ^ B[i];
// Array B for the considered
// value of K
for (int j = 0; j < n; j++) {
C[j] = A[j] ^ candidate;
}
Arrays.sort(C);
boolean flag = false;
// Verify if the considered value
// satisfies the condition or not
for (int j = 0; j < n; j++)
if (C[j] != B[j])
flag = true;
// Insert the possible Bitwise
// XOR value
if (!flag)
numbers.add(candidate);
}
// Print all the values obtained
for (int x : numbers) {
System.out.print(x+ " ");
}
}
// Driver Code
public static void main(String[] args)
{
int A[] = { 7, 8, 14 };
int B[] = { 5, 12, 3 };
int N = A.length;
findPossibleValues(A, B, N);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python program for the above approach
# Function to find all possible values
# of Bitwise XOR such after rearranging
# the array elements the Bitwise XOR
# value at corresponding indexes is same
def findPossibleValues(A, B, n):
# Sort the array B
B.sort();
C = [0] * n;
# Stores all the possible values
# of the Bitwise XOR
numbers = set();
# Iterate over the range
for i in range(n):
# Possible value of K
candidate = A[0] ^ B[i];
# Array B for the considered
# value of K
for j in range(n):
C[j] = A[j] ^ candidate;
C.sort();
flag = False;
# Verify if the considered value
# satisfies the condition or not
for j in range(n):
if (C[j] != B[j]):
flag = True;
# Insert the possible Bitwise
# XOR value
if (not flag):
numbers.add(candidate);
# Print all the values obtained
for x in numbers:
print(x, end = " ");
# Driver Code
A = [7, 8, 14];
B = [5, 12, 3];
N = len(A);
findPossibleValues(A, B, N);
# This code is contributed by gfgking.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
// Function to find all possible values
// of Bitwise XOR such after rearranging
// the array elements the Bitwise XOR
// value at corresponding indexes is same
static void findPossibleValues(int []A, int []B,
int n)
{
// Sort the array B
Array.Sort(B);
int []C = new int[n];
// Stores all the possible values
// of the Bitwise XOR
HashSet<int> numbers = new HashSet<int>();
// Iterate over the range
for (int i = 0; i < n; i++) {
// Possible value of K
int candidate = A[0] ^ B[i];
// Array B for the considered
// value of K
for (int j = 0; j < n; j++) {
C[j] = A[j] ^ candidate;
}
Array.Sort(C);
bool flag = false;
// Verify if the considered value
// satisfies the condition or not
for (int j = 0; j < n; j++)
if (C[j] != B[j])
flag = true;
// Insert the possible Bitwise
// XOR value
if (!flag)
numbers.Add(candidate);
}
// Print all the values obtained
foreach (int x in numbers) {
Console.Write(x+ " ");
}
}
// Driver Code
public static void Main(String[] args)
{
int []A = { 7, 8, 14 };
int []B = { 5, 12, 3 };
int N = A.Length;
findPossibleValues(A, B, N);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program for the above approach
// Function to find all possible values
// of Bitwise XOR such after rearranging
// the array elements the Bitwise XOR
// value at corresponding indexes is same
function findPossibleValues(A, B, n) {
// Sort the array B
B.sort((a, b) => a - b);
let C = new Array(n);
// Stores all the possible values
// of the Bitwise XOR
let numbers = new Set();
// Iterate over the range
for (let i = 0; i < n; i++) {
// Possible value of K
let candidate = A[0] ^ B[i];
// Array B for the considered
// value of K
for (let j = 0; j < n; j++) {
C[j] = A[j] ^ candidate;
}
C.sort((a, b) => a - b);
let flag = false;
// Verify if the considered value
// satisfies the condition or not
for (let j = 0; j < n; j++) if (C[j] != B[j]) flag = true;
// Insert the possible Bitwise
// XOR value
if (!flag) numbers.add(candidate);
}
// Print all the values obtained
for (let x of numbers) {
document.write(x + " ");
}
}
// Driver Code
let A = [7, 8, 14];
let B = [5, 12, 3];
let N = A.length;
findPossibleValues(A, B, N);
// This code is contributed by gfgking.
</script>
Time Complexity: O(N2*log(N))
Auxiliary Space: O(N)
Efficient Approach: The above approach can also be optimized by not sorting the array and store the bit-wise-XOR of all elements of B[], and then the Bitwise XOR with all elements in C[]. Now if the result is 0 then it means both arrays have same elements. Follow the steps below to solve the problem:
- Initialize the variable, say x that stores the XOR of all the elements of the array B[].
- Initialize a set, say numbers[] to store only unique numbers..
- Iterate over the range [0, N) using the variable i and perform the following steps:
- Initialize the variables candidate as the XOR of A[0] and B[i] and curr_xor as x to see if it is 0 after performing the requires operations.
- Iterate over the range [0, N) using the variable j and perform the following steps:
- Initialize the variable y as the XOR of A[j] and candidate and XOR y with curr_xor.
- If curr_xor is equal to 0, then insert the value candidate into the set numbers[].
- After performing the above steps, print the set numbers[] as the answer.
Below is the implementation of the above approach.
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find all possible values
// of Bitwise XOR such after rearranging
// the array elements the Bitwise XOR
// value at corresponding indexes is same
void findPossibleValues(int A[], int B[],
int n)
{
// Stores the XOR of the array B[]
int x = 0;
for (int i = 0; i < n; i++) {
x = x ^ B[i];
}
// Stores all possible value of
// Bitwise XOR
set<int> numbers;
// Iterate over the range
for (int i = 0; i < n; i++) {
// Possible value of K
int candidate = A[0] ^ B[i];
int curr_xor = x;
// Array B for the considered
// value of K
for (int j = 0; j < n; j++) {
int y = A[j] ^ candidate;
curr_xor = curr_xor ^ y;
}
// This means all the elements
// are equal
if (curr_xor == 0)
numbers.insert(candidate);
}
// Print all the possible value
for (auto x : numbers) {
cout << x << " ";
}
}
// Driver Code
int main()
{
int A[] = { 7, 8, 14 };
int B[] = { 5, 12, 3 };
int N = sizeof(A) / sizeof(A[0]);
findPossibleValues(A, B, N);
return 0;
}
Java
// Java code for above approach
import java.util.*;
class GFG{
// Function to find all possible values
// of Bitwise XOR such after rearranging
// the array elements the Bitwise XOR
// value at corresponding indexes is same
static void findPossibleValues(int A[], int B[],
int n)
{
// Stores the XOR of the array B[]
int x = 0;
for (int i = 0; i < n; i++) {
x = x ^ B[i];
}
// Stores all possible value of
// Bitwise XOR
HashSet<Integer> numbers = new HashSet<Integer>();
// Iterate over the range
for (int i = 0; i < n; i++) {
// Possible value of K
int candidate = A[0] ^ B[i];
int curr_xor = x;
// Array B for the considered
// value of K
for (int j = 0; j < n; j++) {
int y = A[j] ^ candidate;
curr_xor = curr_xor ^ y;
}
// This means all the elements
// are equal
if (curr_xor == 0)
numbers.add(candidate);
}
// Print all the possible value
for (int i : numbers) {
System.out.print(i + " ");
}
}
// Driver Code
public static void main(String[] args)
{
int A[] = { 7, 8, 14 };
int B[] = { 5, 12, 3 };
int N = A.length;
findPossibleValues(A, B, N);
}
}
// This code is contributed by avijitmondal1998.
Python3
# Python 3 program for the above approach
# Function to find all possible values
# of Bitwise XOR such after rearranging
# the array elements the Bitwise XOR
# value at corresponding indexes is same
def findPossibleValues(A, B, n):
# Stores the XOR of the array B[]
x = 0
for i in range(n):
x = x ^ B[i]
# Stores all possible value of
# Bitwise XOR
numbers = set()
# Iterate over the range
for i in range(n):
# Possible value of K
candidate = A[0] ^ B[i]
curr_xor = x
# Array B for the considered
# value of K
for j in range(n):
y = A[j] ^ candidate
curr_xor = curr_xor ^ y
# This means all the elements
# are equal
if (curr_xor == 0):
numbers.add(candidate)
# Print all the possible value
for x in numbers:
print(x, end = " ")
# Driver Code
if __name__ == '__main__':
A = [7, 8, 14]
B = [5, 12, 3]
N = len(A)
findPossibleValues(A, B, N)
# This code is contributed by ipg2016107.
C#
// C# code for above approach
using System;
using System.Collections.Generic;
public class GFG
{
// Function to find all possible values
// of Bitwise XOR such after rearranging
// the array elements the Bitwise XOR
// value at corresponding indexes is same
static void findPossibleValues(int []A, int []B,
int n)
{
// Stores the XOR of the array []B
int x = 0;
for (int i = 0; i < n; i++) {
x = x ^ B[i];
}
// Stores all possible value of
// Bitwise XOR
HashSet<int> numbers = new HashSet<int>();
// Iterate over the range
for (int i = 0; i < n; i++) {
// Possible value of K
int candidate = A[0] ^ B[i];
int curr_xor = x;
// Array B for the considered
// value of K
for (int j = 0; j < n; j++) {
int y = A[j] ^ candidate;
curr_xor = curr_xor ^ y;
}
// This means all the elements
// are equal
if (curr_xor == 0)
numbers.Add(candidate);
}
// Print all the possible value
foreach (int i in numbers) {
Console.Write(i + " ");
}
}
// Driver Code
public static void Main(String[] args)
{
int []A = { 7, 8, 14 };
int []B = { 5, 12, 3 };
int N = A.Length;
findPossibleValues(A, B, N);
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// javascript code for above approach
// Function to find all possible values
// of Bitwise XOR such after rearranging
// the array elements the Bitwise XOR
// value at corresponding indexes is same
function findPossibleValues(A, B, n)
{
// Stores the XOR of the array B
var x = 0;
for (var i = 0; i < n; i++) {
x = x ^ B[i];
}
// Stores all possible value of
// Bitwise XOR
var numbers = new Set();
// Iterate over the range
for (var i = 0; i < n; i++) {
// Possible value of K
var candidate = A[0] ^ B[i];
var curr_xor = x;
// Array B for the considered
// value of K
for (var j = 0; j < n; j++) {
var y = A[j] ^ candidate;
curr_xor = curr_xor ^ y;
}
// This means all the elements
// are equal
if (curr_xor == 0)
numbers.add(candidate);
}
// Print all the possible value
for (var i of numbers) {
document.write(i + " ");
}
}
// Driver Code
var A = [ 7, 8, 14 ];
var B = [ 5, 12, 3 ];
var N = A.length;
findPossibleValues(A, B, N);
// This code is contributed by shikhasingrajput
</script>
Time Complexity: O(N2)
Auxiliary Space: O(N) as using set "numbers"
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem