Given an array arr[] of size N and an integer K, the task is to find the length of the longest subarray having Bitwise XOR of all its elements equal to K.
Examples:
Input: arr[] = { 1, 2, 4, 7, 2 }, K = 1
Output: 3
Explanation:
Subarray having Bitwise XOR equal to K(= 1) are { { 1 }, { 2, 4, 7 }, { 1 } }.
Therefore, the length of longest subarray having bitwise XOR equal to K(= 1) is 3
Input: arr[] = { 2, 5, 6, 1, 0, 3, 5, 6 }, K = 4
Output: 6
Explanation:
Subarray having Bitwise XOR equal to K(= 4) are { { 6, 1, 0, 3 }, { 5, 6, 1, 0, 3, 5 } }.
Therefore, the length of longest subarray having bitwise XOR equal to K(= 4) is 6.
Naive Approach
The idea is to generate all subarrays and find that subarray whose bitwise XOR of all elements is equal to K and has a maximum length
Steps to Implement:
- Initialize a variable “ans” with 0 because if no such subarray exists then it will be the answer
- Run two for loops from 0 to N-1 to generate all subarray
- For each subarray find the XOR of all elements and its length
- If any XOR value got equal to K then update “ans” as the maximum of “ans” and the length of that subarray
- In the last print/return value in ans
Code-
C++
#include <bits/stdc++.h>
using namespace std;
int LongestLenXORK( int arr[], int N, int K)
{
int ans=0;
for ( int i=0;i<N;i++){
int length=0;
int temp=0;
for ( int j=i;j<N;j++){
temp=temp^arr[j];
length++;
if (temp==K){
ans=max(ans,length);
}
}
}
return ans;
}
int main()
{
int arr[] = { 1, 2, 4, 7, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
int K = 1;
cout<< LongestLenXORK(arr, N, K);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int LongestLenXORK( int [] arr, int N, int K)
{
int ans = 0 ;
for ( int i = 0 ; i < N; i++) {
int length = 0 ;
int temp = 0 ;
for ( int j = i; j < N; j++) {
temp = temp ^ arr[j];
length++;
if (temp == K) {
ans = Math.max(ans, length);
}
}
}
return ans;
}
public static void main(String[] args)
{
int [] arr = { 1 , 2 , 4 , 7 , 2 };
int N = arr.length;
int K = 1 ;
System.out.println(LongestLenXORK(arr, N, K));
}
}
|
Python3
def LongestLenXORK(arr, N, K):
ans = 0
for i in range (N):
length = 0
temp = 0
for j in range (i, N):
temp ^ = arr[j]
length + = 1
if temp = = K:
ans = max (ans, length)
return ans
if __name__ = = '__main__' :
arr = [ 1 , 2 , 4 , 7 , 2 ]
N = len (arr)
K = 1
print (LongestLenXORK(arr, N, K))
|
C#
using System;
class GFG
{
static int LongestLenXORK( int [] arr, int N, int K)
{
int ans = 0;
for ( int i = 0; i < N; i++)
{
int length = 0;
int temp = 0;
for ( int j = i; j < N; j++)
{
temp ^= arr[j];
length++;
if (temp == K)
{
ans = Math.Max(ans, length);
}
}
}
return ans;
}
static void Main( string [] args)
{
int [] arr = { 1, 2, 4, 7, 2 };
int N = arr.Length;
int K = 1;
Console.WriteLine(LongestLenXORK(arr, N, K));
}
}
|
Javascript
function LongestLenXORK(arr, N, K) {
let ans = 0;
for (let i = 0; i < N; i++) {
let length = 0;
let temp = 0;
for (let j = i; j < N; j++) {
temp ^= arr[j];
length += 1;
if (temp === K) {
ans = Math.max(ans, length);
}
}
}
return ans;
}
const arr = [1, 2, 4, 7, 2];
const N = arr.length;
const K = 1;
console.log(LongestLenXORK(arr, N, K));
|
Output-
3
Time Complexity: O(N2), because of two nested loops from 0 to N-1
Auxiliary Space: O(1), because no extra space has been used
Approach: The problem can be solved using Hashing and Prefix Sum technique. Following are the observation:
a1 ^ a2 ^ a3 ^ ….. ^ an = K
=> a2 ^ a3 ^ ….. ^ an ^ K = a1
Follow the steps below to solve the problem:
- Initialize a variable, say prefixXOR, to store the Bitwise XOR of all elements up to the ith index of the given array.
- Initialize a Map, say mp, to store the indices of the computed prefix XORs of the array.
- Initialize a variable, say maxLen, to store the length of the longest subarray whose Bitwise XOR is equal to K.
- Traverse the array arr[] using variable i. For every ith index, update prefixXOR = prefixXOR ^ arr[i] and check if (prefixXOR ^ K) is present in the Map or not. If found to be true, then update maxLen = max(maxLen, i – mp[prefixXOR ^ K]).
- If prefixXOR is not present in the Map, then insert prefixXOR into the Map.
- Finally, print the value of maxLen.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int LongestLenXORK( int arr[], int N, int K)
{
int prefixXOR = 0;
int maxLen = 0;
unordered_map< int , int > mp;
mp[0] = -1;
for ( int i = 0; i < N; i++) {
prefixXOR ^= arr[i];
if (mp.count(prefixXOR ^ K)) {
maxLen = max(maxLen,
(i - mp[prefixXOR ^ K]));
}
if (!mp.count(prefixXOR)) {
mp[prefixXOR] = i;
}
}
return maxLen;
}
int main()
{
int arr[] = { 1, 2, 4, 7, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
int K = 1;
cout<< LongestLenXORK(arr, N, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int LongestLenXORK( int arr[],
int N, int K)
{
int prefixXOR = 0 ;
int maxLen = 0 ;
HashMap<Integer,
Integer> mp = new HashMap<Integer,
Integer>();
mp.put( 0 , - 1 );
for ( int i = 0 ; i < N; i++)
{
prefixXOR ^= arr[i];
if (mp.containsKey(prefixXOR ^ K))
{
maxLen = Math.max(maxLen,
(i - mp.get(prefixXOR ^ K)));
}
if (!mp.containsKey(prefixXOR))
{
mp.put(prefixXOR, i);
}
}
return maxLen;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 4 , 7 , 2 };
int N = arr.length;
int K = 1 ;
System.out.print(LongestLenXORK(arr, N, K));
}
}
|
Python3
def LongestLenXORK(arr, N, K):
prefixXOR = 0
maxLen = 0
mp = {}
mp[ 0 ] = - 1
for i in range (N):
prefixXOR ^ = arr[i]
if (prefixXOR ^ K) in mp:
maxLen = max (maxLen,
(i - mp[prefixXOR ^ K]))
else :
mp[prefixXOR] = i
return maxLen
if __name__ = = "__main__" :
arr = [ 1 , 2 , 4 , 7 , 2 ]
N = len (arr)
K = 1
print (LongestLenXORK(arr, N, K))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int longestLenXORK( int []arr,
int N, int K)
{
int prefixXOR = 0;
int maxLen = 0;
Dictionary< int ,
int > mp = new Dictionary< int ,
int >();
mp.Add(0, -1);
for ( int i = 0; i < N; i++)
{
prefixXOR ^= arr[i];
if (mp.ContainsKey(prefixXOR ^ K))
{
maxLen = Math.Max(maxLen,
(i - mp[prefixXOR ^ K]));
}
if (!mp.ContainsKey(prefixXOR))
{
mp.Add(prefixXOR, i);
}
}
return maxLen;
}
public static void Main(String[] args)
{
int []arr = {1, 2, 4, 7, 2};
int N = arr.Length;
int K = 1;
Console.Write(longestLenXORK(arr, N, K));
}
}
|
Javascript
<script>
function LongestLenXORK(arr, N, K)
{
var prefixXOR = 0;
var maxLen = 0;
var mp = new Map();
mp.set(0, -1);
for ( var i = 0; i < N; i++) {
prefixXOR ^= arr[i];
if (mp.has(prefixXOR ^ K)) {
maxLen = Math.max(maxLen,
(i - mp.get(prefixXOR ^ K)));
}
if (!mp.has(prefixXOR)) {
mp.set(prefixXOR, i);
}
}
return maxLen;
}
var arr = [1, 2, 4, 7, 2];
var N = arr.length;
var K = 1;
document.write( LongestLenXORK(arr, N, K));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
26 Sep, 2023
Like Article
Save Article