Find the XOR of first half and second half elements of an array
Last Updated :
25 May, 2022
Given an array arr of size N. The task is to find the XOR of the first half (N/2) elements and second half elements (N – N/2) of an array.
Examples:
Input: arr[]={20, 30, 50, 10, 55, 15, 42}
Output: 56, 24
Explanation:
XOR of first half elements 20 ^ 30 ^ 50 is 56
Xor of second half elements 10 ^ 55 ^ 15 ^ 42 is 24
Input: arr[]={50, 45, 36, 6, 8, 87}
Output: 59, 89
Approach:
- Initialize FirstHalfXOR and SecondHalfXOR as 0.
- Traverse the array and XOR elements in FirstHalfXOR until the current index is less than N/2.
- Otherwise, XOR elements in SecondHalfXOR.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void XOROfElements( int arr[], int n){
int FirstHalfXOR = 0;
int SecondHalfXOR = 0;
for ( int i=0; i < n; i++){
if (i < n / 2)
FirstHalfXOR ^= arr[i];
else
SecondHalfXOR ^= arr[i];
}
cout << FirstHalfXOR << "," << SecondHalfXOR << endl;
}
int main() {
int arr[] = {20, 30, 50, 10, 55, 15, 42};
int N = sizeof (arr)/ sizeof (arr[0]);
XOROfElements(arr, N);
return 0;
}
|
Java
class GFG{
static void XOROfElements( int arr[], int n){
int FirstHalfXOR = 0 ;
int SecondHalfXOR = 0 ;
for ( int i = 0 ; i < n; i++){
if (i < n / 2 )
FirstHalfXOR ^= arr[i];
else
SecondHalfXOR ^= arr[i];
}
System.out.print(FirstHalfXOR + ","
+ SecondHalfXOR + "\n" );
}
public static void main(String[] args)
{
int arr[] = { 20 , 30 , 50 , 10 , 55 , 15 , 42 };
int N = arr.length;
XOROfElements(arr, N);
}
}
|
Python3
def XOROfElements(arr, n):
FirstHalfXOR = 0 ;
SecondHalfXOR = 0 ;
for i in range (n):
if (i < n / / 2 ):
FirstHalfXOR ^ = arr[i];
else :
SecondHalfXOR ^ = arr[i];
print (FirstHalfXOR, "," ,SecondHalfXOR);
arr = [ 20 , 30 , 50 , 10 , 55 , 15 , 42 ];
N = len (arr);
XOROfElements(arr, N);
|
C#
using System;
class GFG{
static void XOROfElements( int []arr, int n)
{
int FirstHalfXOR = 0;
int SecondHalfXOR = 0;
for ( int i = 0; i < n; i++)
{
if (i < n / 2)
FirstHalfXOR ^= arr[i];
else
SecondHalfXOR ^= arr[i];
}
Console.Write(FirstHalfXOR + "," +
SecondHalfXOR + "\n" );
}
public static void Main(String[] args)
{
int []arr = { 20, 30, 50, 10, 55, 15, 42 };
int N = arr.Length;
XOROfElements(arr, N);
}
}
|
Javascript
<script>
function XOROfElements(arr , n)
{
var FirstHalfXOR = 0;
var SecondHalfXOR = 0;
for (i = 0; i < n; i++) {
if (i < parseInt(n / 2))
FirstHalfXOR ^= arr[i];
else
SecondHalfXOR ^= arr[i];
}
document.write(
FirstHalfXOR + ", " + SecondHalfXOR + "\n"
);
}
var arr = [ 20, 30, 50, 10, 55, 15, 42 ];
var N = arr.length;
XOROfElements(arr, N);
</script>
|
Time complexity: O(N), as we are using a loop to traverse the array.
Auxiliary Space: O(1), as we are not using any extra space.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...